コード例 #1
5
ファイル: web.go プロジェクト: ChristophPech/servertest
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()))))

}
コード例 #2
1
func TodoIndex(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(todos); err != nil {
		panic(err)
	}
}
コード例 #3
1
ファイル: api.go プロジェクト: juniorz/docker
func postContainersKill(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if vars == nil {
		return fmt.Errorf("Missing parameter")
	}
	if err := parseForm(r); err != nil {
		return err
	}
	name := vars["name"]

	signal := 0
	if r != nil {
		s := r.Form.Get("signal")
		if s != "" {
			if s, err := strconv.Atoi(s); err != nil {
				return err
			} else {
				signal = s
			}
		}
	}
	if err := srv.ContainerKill(name, signal); err != nil {
		return err
	}
	w.WriteHeader(http.StatusNoContent)
	return nil
}
コード例 #4
1
ファイル: mux.go プロジェクト: nofdev/fastforward
// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {

		// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
		// This matches with fix in go 1.2 r.c. 4 for same problem.  Go Issue:
		// http://code.google.com/p/go/issues/detail?id=5252
		url := *req.URL
		url.Path = p
		p = url.String()

		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match RouteMatch
	var handler http.Handler
	if r.Match(req, &match) {
		handler = match.Handler
		setVars(req, match.Vars)
		setCurrentRoute(req, match.Route)
	}
	if handler == nil {
		handler = r.NotFoundHandler
		if handler == nil {
			handler = http.NotFoundHandler()
		}
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
コード例 #5
1
ファイル: blockpage.go プロジェクト: soccerties/redwood
// showBlockPage shows a block page for a page that was blocked by an ACL.
func (c *config) showBlockPage(w http.ResponseWriter, r *http.Request, resp *http.Response, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule) {
	w.WriteHeader(http.StatusForbidden)
	if c.BlockTemplate == nil {
		return
	}
	data := blockData{
		URL:        r.URL.String(),
		Conditions: rule.Conditions(),
		User:       user,
		Tally:      listTally(stringTally(tally)),
		Scores:     listTally(scores),
		Request:    r,
		Response:   resp,
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	// Convert rule conditions into category descriptions as much as possible.
	var categories []string
	for _, acl := range rule.Needed {
		categories = append(categories, c.aclDescription(acl))
	}
	for _, acl := range rule.Disallowed {
		categories = append(categories, "not "+c.aclDescription(acl))
	}
	data.Categories = strings.Join(categories, ", ")

	err := c.BlockTemplate.Execute(w, data)
	if err != nil {
		log.Println("Error filling in block page template:", err)
	}
}
コード例 #6
1
ファイル: httputils.go プロジェクト: cclient/gowebframework
func WriteSuccess(w http.ResponseWriter, code int) error {
	fmt.Println(code)
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(code)
	item := Item{Item: "success"}
	return json.NewEncoder(w).Encode(item)
}
コード例 #7
0
ファイル: swarm.go プロジェクト: cezarsa/go-dockerclient
func (s *DockerServer) serviceDelete(w http.ResponseWriter, r *http.Request) {
	s.swarmMut.Lock()
	defer s.swarmMut.Unlock()
	s.cMut.Lock()
	defer s.cMut.Unlock()
	if s.swarm == nil {
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}
	id := mux.Vars(r)["id"]
	var i int
	var toDelete *swarm.Service
	for i = range s.services {
		if s.services[i].ID == id || s.services[i].Spec.Name == id {
			toDelete = s.services[i]
			break
		}
	}
	if toDelete == nil {
		http.Error(w, "service not found", http.StatusNotFound)
		return
	}
	s.services[i] = s.services[len(s.services)-1]
	s.services = s.services[:len(s.services)-1]
	for i := 0; i < len(s.tasks); i++ {
		if s.tasks[i].ServiceID == toDelete.ID {
			_, contIdx, _ := s.findContainerWithLock(s.tasks[i].Status.ContainerStatus.ContainerID, false)
			if contIdx != -1 {
				s.containers = append(s.containers[:contIdx], s.containers[contIdx+1:]...)
			}
			s.tasks = append(s.tasks[:i], s.tasks[i+1:]...)
			i--
		}
	}
}
コード例 #8
0
ファイル: swarm.go プロジェクト: cezarsa/go-dockerclient
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)
}
コード例 #9
0
// OperatorRaftPeer supports actions on Raft peers. Currently we only support
// removing peers by address.
func (s *HTTPServer) OperatorRaftPeer(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	if req.Method != "DELETE" {
		resp.WriteHeader(http.StatusMethodNotAllowed)
		return nil, nil
	}

	var args structs.RaftPeerByAddressRequest
	s.parseDC(req, &args.Datacenter)
	s.parseToken(req, &args.Token)

	params := req.URL.Query()
	if _, ok := params["address"]; ok {
		args.Address = raft.ServerAddress(params.Get("address"))
	} else {
		resp.WriteHeader(http.StatusBadRequest)
		resp.Write([]byte("Must specify ?address with IP:port of peer to remove"))
		return nil, nil
	}

	var reply struct{}
	if err := s.agent.RPC("Operator.RaftRemovePeerByAddress", &args, &reply); err != nil {
		return nil, err
	}
	return nil, nil
}
コード例 #10
0
ファイル: main.go プロジェクト: qgweb/gopro
//请求出价
func requestPrice(w http.ResponseWriter, r *http.Request) {
	rtotal++
	//http://$ip:$port/uri/?ad=$ad&ua=$ua&url=$url&mid=$mid&showType=01|02|03|04
	query := r.URL.Query()
	//	ad := query.Get("ad")
	//	ua := query.Get("ua")
	//	url := query.Get("url")
	mid := query.Get("mid")
	//	showType := query.Get("showType")

	if mid == "" {
		w.WriteHeader(404)
		return
	}

	param := make(map[string]string)
	for k, v := range query {
		param[k] = v[0]
	}

	go recordAdUa(param)

	//30%概率返回
	rd := getRand([]int{30, 70})
	if rd == 0 {
		go reponsePrice(param)
	}
}
コード例 #11
0
ファイル: server_bid.go プロジェクト: psyvisions/bitwrk
func redirectToBid(bidKey *datastore.Key, w http.ResponseWriter, r *http.Request) {
	bidUrl, _ := url.Parse("/bid/" + bidKey.Encode())
	bidUrl = r.URL.ResolveReference(bidUrl)
	w.Header().Set("Location", bidUrl.RequestURI())
	w.Header().Set("X-Bid-Key", bidKey.Encode())
	w.WriteHeader(http.StatusSeeOther)
}
コード例 #12
0
/**
 * GET A LANGUAGE BY ITS ID
 */
func goGetLanguageById(w http.ResponseWriter, r *http.Request) {
	//parse array of input from request message
	vars := mux.Vars(r)

	//get id input
	var langId string
	langId = vars["languageId"]

	//execute get method
	lang := getLanguageById(langId)

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

	if lang.Id != "" {
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(lang); err != nil {
			panic(err)
		}
		return
	}

	// If we didn't find it, 404
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}

}
コード例 #13
0
ファイル: apiserver.go プロジェクト: F21/kubernetes
// write renders a returned runtime.Object to the response as a stream or an encoded object. If the object
// returned by the response implements rest.ResourceStreamer that interface will be used to render the
// response. The Accept header and current API version will be passed in, and the output will be copied
// directly to the response body. If content type is returned it is used, otherwise the content type will
// be "application/octet-stream". All other objects are sent to standard JSON serialization.
func write(statusCode int, apiVersion string, codec runtime.Codec, object runtime.Object, w http.ResponseWriter, req *http.Request) {
	if stream, ok := object.(rest.ResourceStreamer); ok {
		out, flush, contentType, err := stream.InputStream(apiVersion, req.Header.Get("Accept"))
		if err != nil {
			errorJSONFatal(err, codec, w)
			return
		}
		if out == nil {
			// No output provided - return StatusNoContent
			w.WriteHeader(http.StatusNoContent)
			return
		}
		defer out.Close()
		if len(contentType) == 0 {
			contentType = "application/octet-stream"
		}
		w.Header().Set("Content-Type", contentType)
		w.WriteHeader(statusCode)
		writer := w.(io.Writer)
		if flush {
			writer = flushwriter.Wrap(w)
		}
		io.Copy(writer, out)
		return
	}
	writeJSON(statusCode, codec, object, w, isPrettyPrint(req))
}
コード例 #14
0
ファイル: server3.go プロジェクト: shubhraGupta/cmpe273-lab3
func readKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Simply write some test data for now
	fmt.Println("reading values")

	id := p.ByName("id")
	i, _ := strconv.Atoi(id)

	u := Data{}

	if val, ok := Resp[i]; ok {
		fmt.Println(i, val)
		u.Key = i
		u.Value = val
	}
	// Marshal provided interface into JSON structure

	fmt.Println("before marshalling map :", u)

	uj, _ := json.Marshal(u)

	fmt.Println("after marshalling map :", u)
	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)
}
コード例 #15
0
ファイル: main.go プロジェクト: AgentLee/CS417
func AddStudent(w http.ResponseWriter, r *http.Request) {
	var student Student
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &student); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	// add to db
	//t := RepoCreateTodo(student)
	//w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	//w.WriteHeader(http.StatusCreated)
	//if err := json.NewEncoder(w).Encode(t); err != nil {
	//    panic(err)
	//}
}
コード例 #16
0
func (h *delegateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if h.delegate != nil {
		h.delegate.ServeHTTP(w, req)
		return
	}
	w.WriteHeader(http.StatusNotFound)
}
コード例 #17
0
ファイル: handlers.go プロジェクト: yanchanghai/swarm
// POST /images/load
func postImagesLoad(c *context, w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)

	// call cluster to load image on every node
	wf := NewWriteFlusher(w)
	var errorMessage string
	errorFound := false
	callback := func(what, status string, err error) {
		if err != nil {
			errorFound = true
			errorMessage = err.Error()
			sendJSONMessage(wf, what, fmt.Sprintf("Loading Image... : %s", err.Error()))
			return
		}

		if status == "" {
			sendJSONMessage(wf, what, "Loading Image...")
		} else {
			sendJSONMessage(wf, what, fmt.Sprintf("Loading Image... : %s", status))
		}
	}
	c.cluster.Load(r.Body, callback)
	if errorFound {
		sendErrorJSONMessage(wf, 1, errorMessage)
	}

}
コード例 #18
0
ファイル: swarm.go プロジェクト: cezarsa/go-dockerclient
func (s *DockerServer) nodeUpdate(w http.ResponseWriter, r *http.Request) {
	s.swarmMut.Lock()
	defer s.swarmMut.Unlock()
	if s.swarm == nil {
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}
	id := mux.Vars(r)["id"]
	var n *swarm.Node
	for i := range s.nodes {
		if s.nodes[i].ID == id {
			n = &s.nodes[i]
			break
		}
	}
	if n == nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	var spec swarm.NodeSpec
	err := json.NewDecoder(r.Body).Decode(&spec)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	n.Spec = spec
	err = s.runNodeOperation(s.swarmServer.URL(), nodeOperation{
		Op:   "update",
		Node: *n,
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
コード例 #19
0
ファイル: basic_handlers.go プロジェクト: pratikju/go-chat
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
	}

}
コード例 #20
0
ファイル: api.go プロジェクト: brutus333/prometheus
func respondError(w http.ResponseWriter, apiErr *apiError, data interface{}) {
	w.Header().Set("Content-Type", "application/json")

	var code int
	switch apiErr.typ {
	case errorBadData:
		code = http.StatusBadRequest
	case errorExec:
		code = 422
	case errorCanceled, errorTimeout:
		code = http.StatusServiceUnavailable
	default:
		code = http.StatusInternalServerError
	}
	w.WriteHeader(code)

	b, err := json.Marshal(&response{
		Status:    statusError,
		ErrorType: apiErr.typ,
		Error:     apiErr.err.Error(),
		Data:      data,
	})
	if err != nil {
		return
	}
	w.Write(b)
}
コード例 #21
0
ファイル: put_get_buffered.go プロジェクト: aarzilli/tools
func invalidate(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	ii := instance_mgt.GetByContext(c)

	mkk := r.FormValue("mkk")
	sii := r.FormValue("senderInstanceId")

	if ll > 2 {
		aelog.Infof(c, " %s  ---------  %s\n", sii, mkk)
	}

	w.WriteHeader(http.StatusOK)

	if ii.InstanceID == sii {
		w.Write([]byte("Its ME " + mkk + "\n"))
		w.Write([]byte(sii))
	} else {
		w.Write([]byte("got it " + mkk + "\n"))
		w.Write([]byte(sii + "\n"))
		w.Write([]byte(ii.InstanceID))
	}

}
コード例 #22
0
ファイル: pages.go プロジェクト: denisbakhtin/blog
//PageCreate handles /admin/new_page route
func PageCreate(w http.ResponseWriter, r *http.Request) {
	tmpl := shared.Template(r)
	session := shared.Session(r)
	data := shared.DefaultData(r)
	if r.Method == "GET" {

		data["Title"] = "New page"
		data["Active"] = "pages"
		data["Flash"] = session.Flashes()
		session.Save(r, w)
		tmpl.Lookup("pages/form").Execute(w, data)

	} else if r.Method == "POST" {

		page := &models.Page{
			Name:      r.PostFormValue("name"),
			Content:   r.PostFormValue("content"),
			Published: shared.Atob(r.PostFormValue("published")),
		}

		if err := page.Insert(); err != nil {
			session.AddFlash(err.Error())
			session.Save(r, w)
			http.Redirect(w, r, "/admin/new_page", 303)
			return
		}
		http.Redirect(w, r, "/admin/pages", 303)

	} else {
		err := fmt.Errorf("Method %q not allowed", r.Method)
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(405)
		tmpl.Lookup("errors/405").Execute(w, shared.ErrorData(err))
	}
}
コード例 #23
0
ファイル: tasks.go プロジェクト: asteris-llc/reflex
func (t *TasksHandler) Set(w http.ResponseWriter, r *http.Request) {
	blob, err := ioutil.ReadAll(r.Body)
	if err != nil {
		HandleError(err, w)
		return
	}
	defer r.Body.Close()

	task := new(state.Task)
	err = json.Unmarshal(blob, task)
	if err != nil {
		HandleError(err, w)
		return
	}

	// validate
	if id, ok := mux.Vars(r)["id"]; ok && id != task.ID {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("body ID does not match URL ID"))
		return
	}

	err = t.store.Update(task)
	if err != nil {
		HandleError(err, w)
		return
	}

	headers := w.Header()
	headers.Add("Location", "/1/tasks/"+task.ID)
	w.WriteHeader(http.StatusCreated)
}
コード例 #24
0
func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var todoId int
	var err error
	if todoId, err = strconv.Atoi(vars["todoId"]); err != nil {
		panic(err)
	}

	todo := RepoFindTodo(todoId)
	if todo.Id > 0 {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(todo); err != nil {
			panic(err)
		}
		return
	}

	// If we didn't find it, 404
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}

}
コード例 #25
0
ファイル: server.go プロジェクト: fsouza/go-iam
func (srv *Server) error(w http.ResponseWriter, err *iam.Error) {
	w.WriteHeader(err.StatusCode)
	xmlErr := xmlErrors{Error: *err}
	if e := xml.NewEncoder(w).Encode(xmlErr); e != nil {
		panic(e)
	}
}
コード例 #26
0
ファイル: user.go プロジェクト: khaiql/instagram-go
func Register(w http.ResponseWriter, r *http.Request) {

	user := models.User{}

	if r.FormValue("displayName") != "" {
		user.DisplayName = r.FormValue("displayName")
	} else {
		user.DisplayName = "NULL"
	}

	_email := r.FormValue("email")
	if _email != "" {
		user.Email.Scan(_email)
	}

	if r.FormValue("password") != "" {
		user.Password = r.FormValue("password")
	} else {
		user.Password = "******"
	}

	createUserToken(&user)

	if err := repository.CreateUser(&user).Error; err != nil {
		w.WriteHeader(http.StatusForbidden)
		json.NewEncoder(w).Encode(err)
		return
	}

	log.Println(user)

	json.NewEncoder(w).Encode(user)
}
コード例 #27
0
ファイル: session_endpoint.go プロジェクト: faiq/consul
// SessionDestroy is used to destroy an existing session
func (s *HTTPServer) SessionDestroy(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.SessionRequest{
		Op: structs.SessionDestroy,
	}
	s.parseDC(req, &args.Datacenter)

	// Pull out the session id
	args.Session.ID = strings.TrimPrefix(req.URL.Path, "/v1/session/destroy/")
	if args.Session.ID == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing session"))
		return nil, nil
	}

	var out string
	if err := s.agent.RPC("Session.Apply", &args, &out); err != nil {
		return nil, err
	}
	return true, nil
}
コード例 #28
0
ファイル: avatar.go プロジェクト: pecastro/gogs
func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	urlPath := r.URL.Path
	hash := urlPath[strings.LastIndex(urlPath, "/")+1:]
	size := this.mustInt(r, 80, "s", "size") // default size = 80*80

	avatar := New(hash, this.cacheDir)
	avatar.AlterImage = this.altImage
	if avatar.Expired() {
		if err := avatar.UpdateTimeout(time.Millisecond * 1000); err != nil {
			log.Trace("avatar update error: %v", err)
			return
		}
	}
	if modtime, err := avatar.Modtime(); err == nil {
		etag := fmt.Sprintf("size(%d)", size)
		if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modtime.Before(t.Add(1*time.Second)) && etag == r.Header.Get("If-None-Match") {
			h := w.Header()
			delete(h, "Content-Type")
			delete(h, "Content-Length")
			w.WriteHeader(http.StatusNotModified)
			return
		}
		w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat))
		w.Header().Set("ETag", etag)
	}
	w.Header().Set("Content-Type", "image/jpeg")

	if err := avatar.Encode(w, size); err != nil {
		log.Warn("avatar encode error: %v", err)
		w.WriteHeader(500)
	}
}
コード例 #29
0
func getTripDetails(w http.ResponseWriter, r *http.Request) {
	tripID := r.URL.Query().Get(":tripID")
	fmt.Println(tripID)
	var result UberResponse
	c, s := getMongoCollection("trips")
	defer s.Close()
	err := c.Find(bson.M{"_id": bson.ObjectIdHex(tripID)}).One(&result)
	if err != nil {
		fmt.Println("err = c.Find(bson.M{\"id\": bson.M{\"$oid\":", tripID, "}}).One(&result)")
		log.Fatal(err)
	}

	fmt.Println(result)

	//Returning the result to user
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	outputJSON, err := json.Marshal(result)
	if err != nil {

		w.Write([]byte(`{    "error": "Unable to marshal response. body, 	outputJSON, err := json.Marshal(t) -- line 110"}`))
		panic(err.Error())
	}
	w.Write(outputJSON)

}
コード例 #30
0
ファイル: api_dispatch.go プロジェクト: 10389030/wx-include
func (router *MessageRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		CheckServer(w, r)
	case "POST":
		data, _ := ioutil.ReadAll(r.Body)

		msg := &Message{}
		err := xml.Unmarshal(data, msg)

		if err != nil {
			log.Panic("xml unmarshal post data error: %#v", err)
		}

		if handler, ok := router.handlers[msg.MessageRoute]; ok {
			log.Printf("Handle Found: %#v, %v", msg.MessageRoute, handler)
			handler(w, msg)
		} else {
			log.Printf("Handle Not Found: %#v", msg.MessageRoute)
			if r.ProtoAtLeast(1, 1) {
				w.Header().Set("Connection", "close")
			}
			w.WriteHeader(http.StatusNotFound)
		}

	default:
		log.Printf("unhandle request method: %s", r.Method)
	}
}