当前位置: 首页>>代码示例>>Golang>>正文


Golang http.Error函数代码示例

本文整理汇总了Golang中net/http.Error函数的典型用法代码示例。如果您正苦于以下问题:Golang Error函数的具体用法?Golang Error怎么用?Golang Error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: register

// Create a new user and store that user. Once successfully concluded a JWT
// access token will be returned to the user
func register(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	type payload struct {
		Email    string
		Password string
	}

	pl := payload{}
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&pl)
	if err != nil {
		http.Error(w, "Could not read the given request body", http.StatusBadRequest)
		return
	}

	user, goAuthErr := userService.Register(pl.Email, pl.Password)
	if goAuthErr != nil {
		http.Error(w, goAuthErr.Message, goAuthErr.Status)
		return
	}

	response, err := authResponse(user)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(response)
}
开发者ID:DreamingMatt,项目名称:goauth,代码行数:31,代码来源:auth.go

示例2: wrapBasicAuth

func wrapBasicAuth(handler http.Handler, credential string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := strings.SplitN(r.Header.Get("Authorization"), " ", 2)

		if len(token) != 2 || strings.ToLower(token[0]) != "basic" {
			w.Header().Set("WWW-Authenticate", `Basic realm="GoTTY"`)
			http.Error(w, "Bad Request", http.StatusUnauthorized)
			return
		}

		payload, err := base64.StdEncoding.DecodeString(token[1])
		if err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		if credential != string(payload) {
			w.Header().Set("WWW-Authenticate", `Basic realm="GoTTY"`)
			http.Error(w, "authorization failed", http.StatusUnauthorized)
			return
		}

		log.Printf("Basic Authentication Succeeded: %s", r.RemoteAddr)
		handler.ServeHTTP(w, r)
	})
}
开发者ID:kryptBlue,项目名称:gotty,代码行数:26,代码来源:app.go

示例3: go_get_image

func (ths *ImageTagServer) go_get_image(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Query().Get("path")
	path = ths.imgRoot + path
	path = strings.Replace(path, "..", "", -1)

	info, infoErr := os.Stat(path)
	if infoErr != nil {
		http.Error(w, infoErr.Error(), http.StatusInternalServerError)
		return
	}

	if info.IsDir() == true {
		http.Error(w, "No an image", http.StatusBadRequest)
		return
	}

	img, err := imaging.Open(path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Add("Content-Type", "image/jpeg")
	err = imaging.Encode(w, img, imaging.JPEG)
	if err != nil {
		http.Error(w, "Failed to thumbNail image", http.StatusInternalServerError)
		return
	}

}
开发者ID:rasmuswz,项目名称:imagetag,代码行数:30,代码来源:imagetagserver.go

示例4: ServeHTTP

func (c *ClassifierHandler) ServeHTTP(w http.ResponseWriter,
	req *http.Request) {
	sample := core.NewSample()
	if req.Method != "POST" {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	features := req.FormValue("features")
	if len(features) == 0 {
		http.Error(w, "need input features", http.StatusInternalServerError)
		return
	}
	fs := make(map[string]float64)
	err := json.Unmarshal([]byte(features), &fs)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	for k, v := range fs {
		f := core.Feature{
			Id:    util.Hash(k),
			Value: v,
		}
		sample.AddFeature(f)
	}
	p := c.classifier.Predict(sample)
	output, err := json.Marshal(map[string]interface{}{
		"prediction": p,
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprint(w, output)
}
开发者ID:jamesbjackson,项目名称:hector,代码行数:35,代码来源:hectorserver.go

示例5: postDBIgnores

func (s *apiService) postDBIgnores(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()

	bs, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	var data map[string][]string
	err = json.Unmarshal(bs, &data)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	err = s.model.SetIgnores(qs.Get("folder"), data["ignore"])
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	s.getDBIgnores(w, r)
}
开发者ID:xduugu,项目名称:syncthing,代码行数:25,代码来源:gui.go

示例6: ServeHTTP

func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	oa := CheckAuthorized(w, r, false)
	if oa == nil {
		return
	}
	if r.Method != "POST" {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	m, _, err := r.FormFile("server")
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	defer m.Close()
	dst, err := os.Create(deployFileName)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	_, err = io.Copy(dst, m)
	dst.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	finfo, _ := os.Stat(deployFileName)

	w.WriteHeader(200)
	w.Write([]byte("Uploaded: " + humanize.Bytes(uint64(finfo.Size()))))

}
开发者ID:ChristophPech,项目名称:servertest,代码行数:33,代码来源:web.go

示例7: serviceCreate

func (s *DockerServer) serviceCreate(w http.ResponseWriter, r *http.Request) {
	var config swarm.ServiceSpec
	defer r.Body.Close()
	err := json.NewDecoder(r.Body).Decode(&config)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.cMut.Lock()
	defer s.cMut.Unlock()
	s.swarmMut.Lock()
	defer s.swarmMut.Unlock()
	if len(s.nodes) == 0 || s.swarm == nil {
		http.Error(w, "no swarm nodes available", http.StatusNotAcceptable)
		return
	}
	if config.Name == "" {
		config.Name = s.generateID()
	}
	for _, s := range s.services {
		if s.Spec.Name == config.Name {
			http.Error(w, "there's already a service with this name", http.StatusConflict)
			return
		}
	}
	service := swarm.Service{
		ID:   s.generateID(),
		Spec: config,
	}
	s.addTasks(&service, false)
	s.services = append(s.services, &service)
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(service)
}
开发者ID:cezarsa,项目名称:go-dockerclient,代码行数:34,代码来源:swarm.go

示例8: setComponentHTTP

func (s *Server) setComponentHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	devID := vars["devID"]
	compID := vars["compID"]
	if devID == "" || compID == "" {
		http.Error(w, "must provide device ID and component ID", http.StatusBadRequest)
		return
	}

	// Get the body of the request, which should contain a json-encoded Component
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "error reading request body: "+err.Error(), http.StatusBadRequest)
		return
	}

	// Parse the request as a Component
	asComponent, err := componentFromJSON(body)
	if err != nil {
		http.Error(w, "unable to interpret request body as valid Component: "+err.Error(), http.StatusBadRequest)
		return
	}

	s.setComponent(devID, compID, asComponent)
	http.Redirect(w, r, "/devices/"+devID+"/"+compID, http.StatusSeeOther)
}
开发者ID:upwrd,项目名称:sift,代码行数:26,代码来源:server.go

示例9: encodeHandler

func encodeHandler(response http.ResponseWriter, request *http.Request, db Database, baseURL string) {
	decoder := json.NewDecoder(request.Body)
	var data struct {
		URL string `json:"url"`
	}
	err := decoder.Decode(&data)
	if err != nil {
		http.Error(response, `{"error": "Unable to parse json"}`, http.StatusBadRequest)
		return
	}

	if !govalidator.IsURL(data.URL) {
		http.Error(response, `{"error": "Not a valid URL"}`, http.StatusBadRequest)
		return
	}

	id, err := db.Save(data.URL)
	if err != nil {
		log.Println(err)
		return
	}
	resp := map[string]string{"url": strings.Replace(path.Join(baseURL, encode(id)), ":/", "://", 1), "id": encode(id), "error": ""}
	jsonData, _ := json.Marshal(resp)
	response.Write(jsonData)

}
开发者ID:doomsplayer,项目名称:url-shortener,代码行数:26,代码来源:main.go

示例10: Get

func (i *Incident) Get(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("content-type", "application/json")
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		http.Error(w, "Must append incident id", http.StatusBadRequest)
		return
	}
	index := i.pipeline.GetIndex()

	// if the id is "*", fetch all outstanding incidents
	if id == "*" {
		all := index.ListIncidents()
		all = reduceStatusAbove(event.WARNING, all)
		buff, err := json.Marshal(makeKV(all))
		if err != nil {
			logrus.Error(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(buff)
		return
	}

	// write out the found incident. The value will be null if nothing was found
	in := index.GetIncident([]byte(id))
	buff, err := json.Marshal(in)
	if err != nil {
		logrus.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(buff)
}
开发者ID:postfix,项目名称:bangarang,代码行数:35,代码来源:incident.go

示例11: uploadHandler

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("files")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer file.Close()

	f, err := os.OpenFile("./uploads/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()
	io.Copy(f, file)

	files := Files{
		File{Name: handler.Filename, Type: handler.Header["Content-Type"][0]},
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(files); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

}
开发者ID:pratikju,项目名称:go-chat,代码行数:30,代码来源:basic_handlers.go

示例12: dirHandler

// dirHandler serves a directory listing for the requested path, rooted at basePath.
func dirHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/favicon.ico" {
		http.Error(w, "not found", 404)
		return
	}
	const base = "."
	name := filepath.Join(base, r.URL.Path)

	if isDoc(name) {
		err := renderDoc(w, name)
		if err != nil {
			log.Errorln(err)
			http.Error(w, err.Error(), 500)
		}
		return
	}
	if isDir, err := dirList(w, name); err != nil {
		log.Errorln(err)
		http.Error(w, err.Error(), 500)
		return
	} else if isDir {
		return
	}
	http.FileServer(http.Dir(*f_root)).ServeHTTP(w, r)
}
开发者ID:jenareljam,项目名称:minimega,代码行数:26,代码来源:dir.go

示例13: postRegister

func postRegister(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username, password := r.PostFormValue("username"), r.PostFormValue("password")
	if !recaptcher.Verify(*r) {
		logger.WithFields(logrus.Fields{
			"user":  username,
			"error": recaptcher.LastError(),
		}).Error("Failed to verify reCaptcha during registration.")
		w.Write([]byte("Failed to verify the reCaptcha. Please verify that you are human and try again."))
		return
	}

	err := users.Register(username, password)
	switch err {
	case nil:
		//Success
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   username,
		}).Info("User registration")
		renderer.Render(w, pages.Get(RegistrationSuccessPage))
	case ErrUserExists:
		http.Error(w, "The user already exists. Please try again with a different username.", http.StatusPreconditionFailed)
	default:
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
开发者ID:Victorystick,项目名称:authprox,代码行数:29,代码来源:routes.go

示例14: ServeSubmitAnswer

func ServeSubmitAnswer(store datastores.AnswerStoreServices) m.HandlerFunc {
	return func(c *m.Context, w http.ResponseWriter, r *http.Request) {

		questionID := mux.Vars(r)["questionID"]
		isSlotAvailable, err := store.IsAnswerSlotAvailable(questionID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		} else if !isSlotAvailable {
			http.Error(w, "Maximum capacity for answers has been reached", http.StatusForbidden)
			return
		}

		newAnswer := c.ParsedModel.(*models.Answer)
		requiredRep, err := c.RepStore.FindRep(mux.Vars(r)["category"], c.UserID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}

		err, statusCode := store.StoreAnswer(questionID, c.UserID, newAnswer.Content, services.CalculateCurrentAnswerEligibilityRep(requiredRep))
		if err != nil {
			http.Error(w, err.Error(), statusCode)
			return
		}

		w.WriteHeader(http.StatusCreated)
	}
}
开发者ID:jmheidly,项目名称:Answer-Patch,代码行数:28,代码来源:answer.go

示例15: setDeviceHTTP

func (s *Server) setDeviceHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["devID"]
	if id == "" {
		http.Error(w, "must provide device ID", http.StatusBadRequest)
		return
	}

	// Get the body of the request, which should contain a json-encoded Device
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "error reading request body: "+err.Error(), http.StatusBadRequest)
		return
	}

	// Parse the request as a Device
	asDevice, err := deviceFromJSON(body)
	if err != nil {
		http.Error(w, "unable to interpret request body as valid Device: "+err.Error(), http.StatusBadRequest)
		return
	}

	s.SetDevice(id, asDevice)
	http.Redirect(w, r, "/devices/"+id, http.StatusSeeOther)
}
开发者ID:upwrd,项目名称:sift,代码行数:25,代码来源:server.go


注:本文中的net/http.Error函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。