當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Registry.Config方法代碼示例

本文整理匯總了Golang中github.com/app-kit/go-appkit.Registry.Config方法的典型用法代碼示例。如果您正苦於以下問題:Golang Registry.Config方法的具體用法?Golang Registry.Config怎麽用?Golang Registry.Config使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/app-kit/go-appkit.Registry的用法示例。


在下文中一共展示了Registry.Config方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: notFoundHandler

func notFoundHandler(registry kit.Registry, r kit.Request) (kit.Response, bool) {
	httpRequest := r.GetHttpRequest()
	apiPrefix := "/" + registry.Config().UString("api.prefix", "api")
	isApiRequest := strings.HasPrefix(httpRequest.URL.Path, apiPrefix)

	// Try to render the page on the server, if enabled.
	if !isApiRequest {
		renderEnabled := registry.Config().UBool("serverRenderer.enabled", false)
		noRender := strings.Contains(httpRequest.URL.String(), "no-server-render")

		if renderEnabled && !noRender {
			return serverRenderer(registry, r), false
		}
	}

	// For non-api requests, render the default template.
	if !isApiRequest {
		tpl, err := getIndexTpl(registry)
		if err != nil {
			return kit.NewErrorResponse(err), false
		}
		return &kit.AppResponse{
			RawData: tpl,
		}, false
	}

	// For api requests, render the api not found error.
	return &kit.AppResponse{
		Error: &apperror.Err{
			Code:    "not_found",
			Message: "This api route does not exist",
		},
	}, false
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:34,代碼來源:api.go

示例2: getIndexTpl

func getIndexTpl(registry kit.Registry) ([]byte, apperror.Error) {
	if path := registry.Config().UString("frontend.indexTpl"); path != "" {
		f, err := os.Open(path)
		if err != nil {
			return nil, apperror.Wrap(err, "index_tpl_open_error",
				fmt.Sprintf("The index template at %v could not be opened", path))
		}

		tpl, err := ioutil.ReadAll(f)
		if err != nil {
			return nil, apperror.Wrap(err, "index_tpl_read_error",
				fmt.Sprintf("Could not read index template at %v", path))
		}

		return tpl, nil
	}

	tpl := `
	<html>
		<body>
			<h1>Go Appkit</h1>

			<p>Welcome to your new appkit server.</p>

			<p>
			  Find instructions on how to set up your app at <a href="http://github.com/app-kit/go-appkit">Github</a>
			</p>
		</body>
	</html>
	`

	return []byte(tpl), nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:33,代碼來源:api.go

示例3: ServerErrorMiddleware

func ServerErrorMiddleware(registry kit.Registry, r kit.Request, response kit.Response) (kit.Response, bool) {
	err := response.GetError()
	if err == nil {
		return nil, false
	}

	status := 500

	// If the error is an apperror, and it contains a status,
	// set it as the http status of the response.
	if apperr, ok := err.(apperror.Error); ok {
		if apperr.GetStatus() != 0 {
			status = apperr.GetStatus()
		}
	}

	response.SetHttpStatus(status)

	if response.GetRawData() != nil || response.GetRawDataReader() != nil {
		return nil, false
	}

	httpRequest := r.GetHttpRequest()
	apiPrefix := "/" + registry.Config().UString("api.prefix", "api")
	isApiRequest := strings.HasPrefix(httpRequest.URL.Path, apiPrefix)

	if isApiRequest {
		return nil, false
	}

	data := map[string]interface{}{"errors": []error{response.GetError()}}

	tpl := defaultErrorTpl()

	tplPath := registry.Config().UString("frontend.errorTemplate")
	if tplPath != "" {
		t, err := template.ParseFiles(tplPath)
		if err != nil {
			registry.Logger().Fatalf("Could not parse error template at '%v': %v", tplPath, err)
		} else {
			tpl = t
		}
	}

	var buffer *bytes.Buffer
	if err := tpl.Execute(buffer, data); err != nil {
		registry.Logger().Fatalf("Could not render error template: %v\n", err)
		response.SetRawData([]byte("Server error"))
	} else {
		response.SetRawData(buffer.Bytes())
	}

	return nil, false
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:54,代碼來源:api.go

示例4: New

func New(registry kit.Registry) *Frontend {
	conf := registry.Config()

	f := &Frontend{
		registry:          registry,
		debug:             conf.UBool("frontends.wamp.debug", false),
		beforeMiddlewares: make([]kit.RequestHandler, 0),
		afterMiddlewares:  make([]kit.AfterRequestMiddleware, 0),
		sessions:          make(map[uint]kit.Session),
	}

	f.RegisterBeforeMiddleware(frontends.RequestTraceMiddleware)
	f.RegisterBeforeMiddleware(UnserializerMiddleware)

	f.RegisterAfterMiddleware(frontends.SerializeResponseMiddleware)
	f.RegisterAfterMiddleware(frontends.RequestTraceAfterMiddleware)
	f.RegisterAfterMiddleware(frontends.RequestLoggerMiddleware)

	return f
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:20,代碼來源:wamp.go

示例5: getImageReader

func (r *FilesResource) getImageReader(registry kit.Registry, tmpDir string, file kit.File, width, height int64, filters []string, ip string) (reader kit.ReadSeekerCloser, size int64, err apperror.Error) {
	if width == 0 && height == 0 && len(filters) == 0 {
		reader, err = file.Reader()
		return
	}

	// Dimensions specified.
	// Check if the thumbnail was already created.
	// If so, serve it. Otherwise, create it first.

	if (width == 0 || height == 0) && (file.GetWidth() == 0 || file.GetHeight() == 0) {
		err = &apperror.Err{
			Code:    "image_dimensions_not_determined",
			Message: fmt.Sprintf("The file with id %v does not have width/height", file.GetId()),
		}
		return
	}

	if width < 0 || height < 0 {
		err = apperror.New("invalid_dimensions")
		return
	}

	// If either height or width is 0, determine proper values to presserve aspect ratio.
	if width == 0 {
		ratio := float64(file.GetWidth()) / float64(file.GetHeight())
		width = int64(float64(height) * ratio)
	} else if height == 0 {
		ratio := float64(file.GetHeight()) / float64(file.GetWidth())
		height = int64(float64(width) * ratio)
	}

	maxWidth := registry.Config().UInt("files.thumbGenerator.maxWidth", 2000)
	maxHeight := registry.Config().UInt("files.thumbGenerator.maxHeight", 2000)

	if width > int64(maxWidth) || height > int64(maxHeight) {
		err = &apperror.Err{
			Code:    "dimensions_exceed_maximum_limits",
			Message: "The specified dimensions exceed the maximum limits",
		}
		return
	}

	thumbId := fmt.Sprintf("%v_%v_%v_%v_%v_%v.%v",
		file.GetId(),
		file.GetBucket(),
		file.GetName(),
		strconv.FormatInt(width, 10),
		strconv.FormatInt(height, 10),
		strings.Replace(strings.Join(filters, "_"), ":", "_", -1),
		"jpeg")

	if ok, _ := file.GetBackend().HasFileById("thumbs", thumbId); !ok {
		var channel chan bool
		channel, err = r.thumbnailRateLimiter.Start(ip)
		if err != nil {
			return
		}
		if channel != nil {
			<-channel
		}

		// Thumb does not exist yet, so create it.
		reader, err = file.Reader()
		if err != nil {
			return
		}
		defer reader.Close()

		img, _, err2 := image.Decode(reader)
		if err2 != nil {
			err = apperror.Wrap(err2, "image_decode_error")
			return
		}

		var giftFilters []gift.Filter

		if !(height == 0 && width == 0) {
			giftFilters = append(giftFilters, gift.ResizeToFill(int(width), int(height), gift.LanczosResampling, gift.CenterAnchor))
		}

		for _, filter := range filters {
			if filter == "" {
				continue
			}

			parts := strings.Split(filter, ":")

			if len(parts) > 1 {
				filter = parts[0]
			}

			switch filter {
			case "sepia":
				n := float32(100)

				if len(parts) == 2 {
					x, err2 := strconv.ParseFloat(parts[1], 64)
					if err2 == nil {
						n = float32(x)
//.........這裏部分代碼省略.........
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:101,代碼來源:resource.go

示例6: serverRenderer

func serverRenderer(registry kit.Registry, r kit.Request) kit.Response {
	url := r.GetHttpRequest().URL

	// Build the url to query.
	if url.Scheme == "" {
		url.Scheme = "http"
	}
	if url.Host == "" {
		url.Host = registry.Config().UString("host", "localhost") + ":" + registry.Config().UString("port", "8000")
	}

	q := url.Query()
	q.Set("no-server-render", "1")
	url.RawQuery = q.Encode()

	strUrl := url.String()

	cacheKey := "serverrenderer_" + strUrl
	cacheName := registry.Config().UString("serverRenderer.cache")
	var cache kit.Cache

	// If a cache is specified, try to retrieve it.
	if cacheName != "" {
		cache = registry.Cache(cacheName)
		if cache == nil {
			registry.Logger().Errorf("serverRenderer.cache is set to %v, but the cache is not registered with app", cacheName)
		}
	}

	// If a cache was found, try to retrieve cached response.
	if cache != nil {
		item, err := cache.Get(cacheKey)
		if err != nil {
			registry.Logger().Errorf("serverRenderer: cache retrieval error: %v", err)
		} else if item != nil {
			// Cache item found, return response with cache item.
			status, _ := strconv.ParseInt(item.GetTags()[0], 10, 64)
			data, _ := item.ToString()

			return &kit.AppResponse{
				HttpStatus: int(status),
				RawData:    []byte(data),
			}
		}
	}

	// Either no cache or url not yet cached, so render it.

	// First, ensure that the tmp directory exists.
	tmpDir := path.Join(registry.Config().TmpDir(), "phantom")
	if ok, _ := utils.FileExists(tmpDir); !ok {
		if err := os.MkdirAll(tmpDir, 0777); err != nil {
			return &kit.AppResponse{
				Error: &apperror.Err{
					Code:    "create_tmp_dir_failed",
					Message: fmt.Sprintf("Could not create the tmp directory at %v: %v", tmpDir, err),
				},
			}
		}
	}

	// Build a unique file name.
	filePath := path.Join(tmpDir, utils.UUIdv4()+".html")

	// Execute phantom js.

	// Find path of phantom script.
	_, filename, _, _ := runtime.Caller(1)
	scriptPath := path.Join(path.Dir(path.Dir(filename)), "phantom", "render.js")

	start := time.Now()

	phantomPath := registry.Config().UString("serverRenderer.phantomJsPath", "phantomjs")

	args := []string{
		"--web-security=false",
		"--local-to-remote-url-access=true",
		scriptPath,
		"10",
		strUrl,
		filePath,
	}
	result, err := exec.Command(phantomPath, args...).CombinedOutput()
	if err != nil {
		registry.Logger().Errorf("Phantomjs execution error: %v", string(result))

		return &kit.AppResponse{
			Error: apperror.Wrap(err, "phantom_execution_failed"),
		}
	}

	// Get time taken as milliseconds.
	timeTaken := int(time.Now().Sub(start) / time.Millisecond)
	registry.Logger().WithFields(log.Fields{
		"action":       "phantomjs_render",
		"milliseconds": timeTaken,
	}).Debugf("Rendered url %v with phantomjs", url)

	content, err2 := utils.ReadFile(filePath)
	if err2 != nil {
//.........這裏部分代碼省略.........
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:101,代碼來源:api.go

示例7: HttpHandler

func HttpHandler(w http.ResponseWriter, r *http.Request, params httprouter.Params, registry kit.Registry, handler kit.RequestHandler) {
	config := registry.Config()
	header := w.Header()

	// Set Access-Control headers.
	allowedOrigins := config.UString("accessControl.allowedOrigins", "*")
	header.Set("Access-Control-Allow-Origin", allowedOrigins)

	methods := config.UString("accessControl.allowedMethods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
	header.Set("Access-Control-Allow-Methods", methods)

	allowedHeaders := config.UString("accessControl.allowedHeaders", "Authentication, Content-Type, X-Requested-With, Accept, Accept-Language, Content-Language")
	header.Set("Access-Control-Allow-Headers", allowedHeaders)

	// If it is an options request, just respond with 200.
	if r.Method == "OPTIONS" {
		w.WriteHeader(200)
		return
	}

	request := kit.NewRequest()
	request.SetFrontend("http")
	request.SetPath(r.URL.String())
	request.SetHttpMethod(r.Method)
	request.SetHttpRequest(r)
	request.SetHttpResponseWriter(w)

	for _, param := range params {
		request.Context.Set(param.Key, param.Value)
	}

	queryVals := r.URL.Query()
	for key := range queryVals {
		vals := queryVals[key]
		if len(vals) == 1 {
			request.Context.Set(key, vals[0])
		} else {
			request.Context.Set(key, vals)
		}
	}

	response, skip := processRequest(registry, request, handler)
	if skip {
		return
	}

	// If a data reader is set, write the data of the reader.
	reader := response.GetRawDataReader()
	if reader != nil {
		w.WriteHeader(response.GetHttpStatus())
		io.Copy(w, reader)
		reader.Close()
		return
	}

	// If raw data is set, write the raw data.
	rawData := response.GetRawData()
	if rawData != nil {
		w.WriteHeader(response.GetHttpStatus())
		w.Write(rawData)
		return
	}

	registry.Logger().Panicf("Invalid response with no raw data: %+v", response)
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:65,代碼來源:api.go


注:本文中的github.com/app-kit/go-appkit.Registry.Config方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。