Example #1
5
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()))))

}
Example #2
1
// 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)
}
Example #3
1
// SessionRenew is used to renew the TTL on an existing TTL session
func (s *HTTPServer) SessionRenew(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.SessionSpecificRequest{}
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}

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

	var out structs.IndexedSessions
	if err := s.agent.RPC("Session.Renew", &args, &out); err != nil {
		return nil, err
	} else if out.Sessions == nil {
		resp.WriteHeader(404)
		resp.Write([]byte(fmt.Sprintf("Session id '%s' not found", args.Session)))
		return nil, nil
	}

	return out.Sessions, nil
}
Example #4
1
func raw_balance(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	w.Write([]byte(wallet.UpdateBalanceFolder()))
}
Example #5
0
func postImagesInsert(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := parseForm(r); err != nil {
		return err
	}

	url := r.Form.Get("url")
	path := r.Form.Get("path")
	if vars == nil {
		return fmt.Errorf("Missing parameter")
	}
	name := vars["name"]
	if version > 1.0 {
		w.Header().Set("Content-Type", "application/json")
	}
	sf := utils.NewStreamFormatter(version > 1.0)
	err := srv.ImageInsert(name, url, path, w, sf)
	if err != nil {
		if sf.Used() {
			w.Write(sf.FormatError(err))
			return nil
		}
		return err
	}

	return nil
}
Example #6
0
func dl_balance(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	wallet.UpdateBalanceFolder()
	buf := new(bytes.Buffer)
	zi := zip.NewWriter(buf)
	filepath.Walk("balance/", func(path string, fi os.FileInfo, err error) error {
		if !fi.IsDir() {
			f, _ := zi.Create(path)
			if f != nil {
				da, _ := ioutil.ReadFile(path)
				f.Write(da)
			}
		}
		return nil
	})
	if zi.Close() == nil {
		w.Header()["Content-Type"] = []string{"application/zip"}
		w.Write(buf.Bytes())
	} else {
		w.Write([]byte("Error"))
	}
}
Example #7
0
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)
}
Example #8
0
func getPostsSince(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)

	id := params["channel_id"]
	if len(id) != 26 {
		c.SetInvalidParam("getPostsSince", "channelId")
		return
	}

	time, err := strconv.ParseInt(params["time"], 10, 64)
	if err != nil {
		c.SetInvalidParam("getPostsSince", "time")
		return
	}

	cchan := Srv.Store.Channel().CheckPermissionsTo(c.TeamId, id, c.Session.UserId)
	pchan := Srv.Store.Post().GetPostsSince(id, time)

	if !c.HasPermissionsToChannel(cchan, "getPostsSince") {
		return
	}

	if result := <-pchan; result.Err != nil {
		c.Err = result.Err
		return
	} else {
		list := result.Data.(*model.PostList)

		w.Write([]byte(list.ToJson()))
	}

}
Example #9
0
func CentralGetRoot(w http.ResponseWriter, r *http.Request) {
	readOnly := context.Get(r, "readOnly").(bool)
	if readOnly {
		w.Write([]byte(`{
    paths: {
        GET: [
            "/configs",
            "/configs/:hostname",
            "/stats",
            "/stats/:hostname"
        ]
    }
}`))

	} else {
		w.Write([]byte(`{
    paths: {
        GET: [
            "/configs",
            "/configs/:hostname",
            "/stats",
            "/stats/:hostname"
        ],
        POST: [
            "/configs",
            "/stats"
        ]
    }
}`))
	}

}
Example #10
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
}
Example #11
0
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)
}
Example #12
0
func (sq *SubmitQueue) servePriorityInfo(res http.ResponseWriter, req *http.Request) {
	res.Header().Set("Content-type", "text/plain")
	res.WriteHeader(http.StatusOK)
	res.Write([]byte(`The merge queue is sorted by the following. If there is a tie in any test the next test will be used. A P0 will always come before a P1, no matter how the other tests compare.
<ol>
  <li>Priority
    <ul>
      <li>Determined by a label of the form 'priority/pX'
      <li>P0 -&gt; P1 -&gt; P2</li>
      <li>A PR with no priority label is considered equal to a P3</li>
      <li>A PR with the '` + retestNotRequiredLabel + `' or '` + retestNotRequiredDocsOnlyLabel + `' label will come first, before even P0</li>
    </ul>
  </li>
  <li>Release milestone due date
    <ul>
      <li>Release milestones are of the form vX.Y where X and Y are integers</li>
      <li>Other milestones are ignored.
      <li>PR with no release milestone will be considered after any PR with a milestone</li>
    </ul>
  </li>
  <li>First time at which the LGTM label was applied.
    <ul>
      <li>This means all PRs start at the bottom of the queue (within their priority and milestone bands, of course) and progress towards the top.</li>
    </ul>
  </li>
</ol> `))
}
Example #13
0
// Base handler for HTTP requests.
func (*handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	if strings.HasPrefix(path, "/css/") {
		path = strings.TrimLeft(path, "/css/")
		if css, ok := assets.Css[path]; ok {
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
			w.Write([]byte(css))
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	} else if path == "/favicon.ico" {
	} else {
		var file []byte

		path = strings.TrimLeft(path, "/")
		if path == "" {
			file = markdown.GetReadme()
		} else {
			file = markdown.GetFile(path)
		}
		data := data{
			Title:   "Knowledge Base",
			Index:   template.HTML(string(markdown.GetIndex())),
			Content: template.HTML(string(file)),
		}
		render(w, data)
	}
}
Example #14
0
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)
	}
}
Example #15
0
func teamList(w http.ResponseWriter, r *http.Request, t *auth.Token) error {
	u, err := t.User()
	if err != nil {
		return err
	}
	rec.Log(u.Email, "list-teams")
	teams, err := u.Teams()
	if err != nil {
		return err
	}
	if len(teams) > 0 {
		var result []map[string]string
		for _, team := range teams {
			result = append(result, map[string]string{"name": team.Name})
		}
		b, err := json.Marshal(result)
		if err != nil {
			return err
		}
		n, err := w.Write(b)
		if err != nil {
			return err
		}
		if n != len(b) {
			return &errors.HTTP{Code: http.StatusInternalServerError, Message: "Failed to write response body."}
		}
	} else {
		w.WriteHeader(http.StatusNoContent)
	}
	return nil
}
Example #16
0
func getPostById(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)

	postId := params["post_id"]
	if len(postId) != 26 {
		c.SetInvalidParam("getPostById", "postId")
		return
	}

	if result := <-Srv.Store.Post().Get(postId); result.Err != nil {
		c.Err = result.Err
		return
	} else {
		list := result.Data.(*model.PostList)

		if len(list.Order) != 1 {
			c.Err = model.NewLocAppError("getPostById", "api.post_get_post_by_id.get.app_error", nil, "")
			return
		}
		post := list.Posts[list.Order[0]]

		cchan := Srv.Store.Channel().CheckPermissionsTo(c.TeamId, post.ChannelId, c.Session.UserId)
		if !c.HasPermissionsToChannel(cchan, "getPostById") {
			return
		}

		if HandleEtag(list.Etag(), w, r) {
			return
		}

		w.Header().Set(model.HEADER_ETAG_SERVER, list.Etag())
		w.Write([]byte(list.ToJson()))
	}
}
Example #17
0
func createPost(c *Context, w http.ResponseWriter, r *http.Request) {
	post := model.PostFromJson(r.Body)
	if post == nil {
		c.SetInvalidParam("createPost", "post")
		return
	}

	// Create and save post object to channel
	cchan := Srv.Store.Channel().CheckPermissionsTo(c.TeamId, post.ChannelId, c.Session.UserId)

	if !c.HasPermissionsToChannel(cchan, "createPost") {
		return
	}

	if rp, err := CreatePost(c, post, true); err != nil {
		c.Err = err

		if c.Err.Id == "api.post.create_post.root_id.app_error" ||
			c.Err.Id == "api.post.create_post.channel_root_id.app_error" ||
			c.Err.Id == "api.post.create_post.parent_id.app_error" {
			c.Err.StatusCode = http.StatusBadRequest
		}

		return
	} else {
		if result := <-Srv.Store.Channel().UpdateLastViewedAt(post.ChannelId, c.Session.UserId); result.Err != nil {
			l4g.Error(utils.T("api.post.create_post.last_viewed.error"), post.ChannelId, c.Session.UserId, result.Err)
		}

		w.Write([]byte(rp.ToJson()))
	}
}
Example #18
0
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)

}
Example #19
0
func PortBindingCreate(w http.ResponseWriter, r *http.Request) {
	port := r.FormValue("port")
	host := r.FormValue("host")
	hostPort := r.FormValue("host_port")
	currentHost, err := h.GetCurrentHost()
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	_, binding, err := getPortBinding(port, true)
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	binding.AddBackend(host, hostPort)
	err = currentHost.Persist()
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	go binding.Start()
	content, err := json.Marshal(binding)
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	log.Println("exposed " + binding.String())
	w.Write(content)
}
Example #20
0
func json_status(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	var out struct {
		Height    uint32
		Hash      string
		Timestamp uint32
		Received  int64
		Time_now  int64
		Diff      float64
	}
	common.Last.Mutex.Lock()
	out.Height = common.Last.Block.Height
	out.Hash = common.Last.Block.BlockHash.String()
	out.Timestamp = common.Last.Block.Timestamp()
	out.Received = common.Last.Time.Unix()
	out.Time_now = time.Now().Unix()
	out.Diff = btc.GetDifficulty(common.Last.Block.Bits())
	common.Last.Mutex.Unlock()

	bx, er := json.Marshal(out)
	if er == nil {
		w.Header()["Content-Type"] = []string{"application/json"}
		w.Write(bx)
	} else {
		println(er.Error())
	}
}
Example #21
0
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))
	}

}
Example #22
0
func json_system(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	var out struct {
		Blocks_cached    int
		Known_peers      int
		Node_uptime      uint64
		Net_block_qsize  int
		Net_tx_qsize     int
		Heap_size        uint64
		Heap_sysmem      uint64
		Qdb_extramem     int64
		Ecdsa_verify_cnt uint64
	}

	out.Blocks_cached = len(network.CachedBlocks)
	out.Known_peers = peersdb.PeerDB.Count()
	out.Node_uptime = uint64(time.Now().Sub(common.StartTime).Seconds())
	out.Net_block_qsize = len(network.NetBlocks)
	out.Net_tx_qsize = len(network.NetTxs)
	out.Heap_size, out.Heap_sysmem = sys.MemUsed()
	out.Qdb_extramem = qdb.ExtraMemoryConsumed
	out.Ecdsa_verify_cnt = btc.EcdsaVerifyCnt

	bx, er := json.Marshal(out)
	if er == nil {
		w.Header()["Content-Type"] = []string{"application/json"}
		w.Write(bx)
	} else {
		println(er.Error())
	}
}
Example #23
0
func getTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)

	offset, err := strconv.Atoi(params["offset"])
	if err != nil {
		c.SetInvalidParam("getTeamMembers", "offset")
		return
	}

	limit, err := strconv.Atoi(params["limit"])
	if err != nil {
		c.SetInvalidParam("getTeamMembers", "limit")
		return
	}

	if c.Session.GetTeamByTeamId(c.TeamId) == nil {
		if !HasPermissionToTeamContext(c, c.TeamId, model.PERMISSION_MANAGE_SYSTEM) {
			return
		}
	}

	if result := <-Srv.Store.Team().GetMembers(c.TeamId, offset, limit); result.Err != nil {
		c.Err = result.Err
		return
	} else {
		members := result.Data.([]*model.TeamMember)
		w.Write([]byte(model.TeamMembersToJson(members)))
		return
	}
}
Example #24
0
func revokeAllSessions(c *Context, w http.ResponseWriter, r *http.Request) {
	props := model.MapFromJson(r.Body)
	id := props["id"]

	if result := <-Srv.Store.Session().Get(id); result.Err != nil {
		c.Err = result.Err
		return
	} else {
		session := result.Data.(*model.Session)

		c.LogAudit("revoked_all=" + id)

		if session.IsOAuth {
			RevokeAccessToken(session.Token)
		} else {
			sessionCache.Remove(session.Token)

			if result := <-Srv.Store.Session().Remove(session.Id); result.Err != nil {
				c.Err = result.Err
				return
			} else {
				w.Write([]byte(model.MapToJson(props)))
				return
			}
		}
	}
}
Example #25
0
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)
}
Example #26
0
func getTeamStats(c *Context, w http.ResponseWriter, r *http.Request) {
	if c.Session.GetTeamByTeamId(c.TeamId) == nil {
		if !HasPermissionToContext(c, model.PERMISSION_MANAGE_SYSTEM) {
			return
		}
	}

	tchan := Srv.Store.Team().GetTotalMemberCount(c.TeamId)
	achan := Srv.Store.Team().GetActiveMemberCount(c.TeamId)

	stats := &model.TeamStats{}
	stats.TeamId = c.TeamId

	if result := <-tchan; result.Err != nil {
		c.Err = result.Err
		return
	} else {
		stats.TotalMemberCount = result.Data.(int64)
	}

	if result := <-achan; result.Err != nil {
		c.Err = result.Err
		return
	} else {
		stats.ActiveMemberCount = result.Data.(int64)
	}

	w.Write([]byte(stats.ToJson()))
}
Example #27
0
// 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
}
Example #28
0
func pubHandler(w http.ResponseWriter, req *http.Request) {
	name := req.FormValue("topic")
	if name == "" {
		http.Error(w, "missing topic", 403)
		return
	}
	size, err := strconv.Atoi(req.FormValue("size"))
	if err != nil {
		http.Error(w, err.Error(), 403)
		return
	}

	var (
		msg    *message.Ins
		header message.Header
		msgs   = make([]*message.Ins, 0, size)
	)
	for !logex.Equal(err, io.EOF) {
		msg, err = message.ReadMessage(&header, req.Body, message.RF_DEFAULT)
		if err != nil {
			break
		}
		msgs = append(msgs, msg)
	}

	t, err := getTopic(name)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	t.PutSync(msgs)
	w.Write([]byte("hello"))
}
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)

}
Example #30
0
// HTML renders HTML content and sends it back to the HTTP client.
func HTML(w http.ResponseWriter, opts Options) error {
	if w == nil {
		return ErrNilResponseWriter
	}

	if opts.Template == nil {
		return ErrNilHTMLTemplate
	}

	headers := w.Header()
	headers.Set("Content-Type", "text/html; charset=utf-8")

	maxAge := strconv.FormatFloat(opts.STSMaxAge.Seconds(), 'f', -1, 64)
	headers.Set("Strict-Transport-Security", "max-age="+maxAge)
	headers.Set("X-Frame-Options", "SAMEORIGIN")
	headers.Set("X-XSS-Protection", "1; mode=block")
	headers.Set("X-Content-Type-Options", "nosniff")

	cache(headers, opts)

	if opts.Status <= 0 {
		opts.Status = http.StatusOK
	}

	buf := new(bytes.Buffer)
	if err := opts.Template.Execute(buf, opts.Data); err != nil {
		log.Printf("[ERROR] %v", err)
	}

	headers.Set("Content-Length", strconv.Itoa(buf.Len()))
	w.WriteHeader(opts.Status)
	w.Write(buf.Bytes())

	return nil
}