本文整理匯總了Golang中github.com/MG-RAST/golib/stretchr/goweb/context.Context.HttpResponseWriter方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.HttpResponseWriter方法的具體用法?Golang Context.HttpResponseWriter怎麽用?Golang Context.HttpResponseWriter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/MG-RAST/golib/stretchr/goweb/context.Context
的用法示例。
在下文中一共展示了Context.HttpResponseWriter方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Handle
// Handle writes the error from the context into the HttpResponseWriter with a
// 500 http.StatusInternalServerError status code.
func (h *DefaultErrorHandler) Handle(ctx context.Context) (stop bool, err error) {
var handlerError HandlerError = ctx.Data().Get(DataKeyForError).Data().(HandlerError)
hostname, _ := os.Hostname()
w := ctx.HttpResponseWriter()
// write the error out
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("<!DOCTYPE html><html><head>"))
w.Write([]byte("<style>"))
w.Write([]byte("h1 { font-size: 17px }"))
w.Write([]byte("h1 strong {text-decoration:underline}"))
w.Write([]byte("h2 { background-color: #ffd; padding: 20px }"))
w.Write([]byte("footer { margin-top: 20px; border-top:1px solid black; padding:10px; font-size:0.9em }"))
w.Write([]byte("</style>"))
w.Write([]byte("</head><body>"))
w.Write([]byte(fmt.Sprintf("<h1>Error in <code>%s</code></h1><h2>%s</h2>", handlerError.Handler, handlerError)))
w.Write([]byte(fmt.Sprintf("<h3><code>%s</code> error in Handler <code>%v</code></h3> <code><pre>%s</pre></code>", reflect.TypeOf(handlerError.OriginalError), &handlerError.Handler, handlerError.Handler)))
w.Write([]byte(fmt.Sprintf("on %s", hostname)))
w.Write([]byte("<footer>Learn more about <a href='http://github.com/stretchr/goweb' target='_blank'>Goweb</a></footer>"))
w.Write([]byte("</body></html>"))
// responses are actually ignored
return false, nil
}
示例2: WriteResponseObject
// WriteResponseObject writes the status code and response object to the HttpResponseWriter in
// the specified context, in the format best suited based on the request.
//
// Goweb uses the WebCodecService to decide which codec to use when responding
// see http://godoc.org/github.com/stretchr/codecs/services#WebCodecService for more information.
//
// This method should be used when the Goweb Standard Response Object does not satisfy the needs of
// the API, but other Respond* methods are recommended.
func (a *GowebAPIResponder) WriteResponseObject(ctx context.Context, status int, responseObject interface{}) error {
service := a.GetCodecService()
acceptHeader := ctx.HttpRequest().Header.Get("Accept")
extension := ctx.FileExtension()
hasCallback := len(ctx.QueryValue(CallbackParameter)) > 0
codec, codecError := service.GetCodecForResponding(acceptHeader, extension, hasCallback)
if codecError != nil {
return codecError
}
options := ctx.CodecOptions()
// do we need to add some options?
if _, exists := options[constants.OptionKeyClientCallback]; hasCallback && !exists {
options[constants.OptionKeyClientCallback] = ctx.QueryValue(CallbackParameter)
}
output, marshalErr := service.MarshalWithCodec(codec, responseObject, options)
if marshalErr != nil {
return marshalErr
}
// use the HTTP responder to respond
ctx.HttpResponseWriter().Header().Set("Content-Type", codec.ContentType()) // TODO: test me
a.httpResponder.With(ctx, status, output)
return nil
}
示例3: With
// With writes a response to the request in the specified context.
func (r *GowebHTTPResponder) With(ctx context.Context, httpStatus int, body []byte) error {
r.WithStatus(ctx, httpStatus)
_, writeErr := ctx.HttpResponseWriter().Write(body)
return writeErr
}
示例4: WithStatus
// WithStatus writes the specified HTTP Status Code to the Context's ResponseWriter.
//
// If the Always200ParamName parameter is present, it will ignore the httpStatus argument,
// and always write net/http.StatusOK (200).
func (r *GowebHTTPResponder) WithStatus(ctx context.Context, httpStatus int) error {
// check for always200
if len(ctx.FormValue(Always200ParamName)) > 0 {
// always return OK
httpStatus = http.StatusOK
}
ctx.HttpResponseWriter().WriteHeader(httpStatus)
return nil
}
示例5: WithStatusText
// WithStatusText writes the specified HTTP Status Code to the Context's ResponseWriter and
// includes a body with the default status text.
func (r *GowebHTTPResponder) WithStatusText(ctx context.Context, httpStatus int) error {
writeStatusErr := r.WithStatus(ctx, httpStatus)
if writeStatusErr != nil {
return writeStatusErr
}
// write the body header
_, writeErr := ctx.HttpResponseWriter().Write([]byte(http.StatusText(httpStatus)))
return writeErr
}
示例6: streamDownload
func streamDownload(ctx context.Context, n *node.Node, filename string) {
nf, err := n.FileReader()
defer nf.Close()
if err != nil {
// File not found or some sort of file read error.
// Probably deserves more checking
err_msg := "err:@preAuth node.FileReader: " + err.Error()
logger.Error(err_msg)
responder.RespondWithError(ctx, 500, err_msg)
return
}
s := &request.Streamer{R: []file.SectionReader{nf}, W: ctx.HttpResponseWriter(), ContentType: "application/octet-stream", Filename: filename, Size: n.File.Size, Filter: nil}
err = s.Stream()
if err != nil {
// causes "multiple response.WriteHeader calls" error but better than no response
err_msg := "err:@preAuth: s.stream: " + err.Error()
logger.Error(err_msg)
responder.RespondWithError(ctx, 500, err_msg)
}
return
}
示例7: streamDownload
// handle download and its options
func streamDownload(ctx context.Context, n *node.Node, options map[string]string) {
nf, err := n.FileReader()
defer nf.Close()
if err != nil {
// File not found or some sort of file read error.
// Probably deserves more checking
err_msg := "err:@preAuth node.FileReader: " + err.Error()
logger.Error(err_msg)
responder.RespondWithError(ctx, 500, err_msg)
return
}
// set defaults
filename := n.Id
var filterFunc filter.FilterFunc = nil
var compressionFormat string = ""
// use options if exist
if fn, has := options["filename"]; has {
filename = fn
}
if fl, has := options["filter"]; has {
if filter.Has(fl) {
filterFunc = filter.Filter(fl)
}
}
if cp, has := options["compression"]; has {
if archive.IsValidCompress(cp) {
compressionFormat = cp
}
}
// stream it
s := &request.Streamer{R: []file.SectionReader{nf}, W: ctx.HttpResponseWriter(), ContentType: "application/octet-stream", Filename: filename, Size: n.File.Size, Filter: filterFunc, Compression: compressionFormat}
err = s.Stream(false)
if err != nil {
// causes "multiple response.WriteHeader calls" error but better than no response
err_msg := "err:@preAuth: s.stream: " + err.Error()
logger.Error(err_msg)
responder.RespondWithError(ctx, 500, err_msg)
}
return
}
示例8: WithPermanentRedirect
// WithPermanentRedirect responds with a redirection to the specific path or URL with the
// http.StatusMovedPermanently status.
func (r *GowebHTTPResponder) WithPermanentRedirect(ctx context.Context, pathOrURLSegments ...interface{}) error {
ctx.HttpResponseWriter().Header().Set("Location", paths.PathFromSegments(pathOrURLSegments...))
return r.WithStatus(ctx, http.StatusMovedPermanently)
}
示例9: Read
//.........這裏部分代碼省略.........
if !seek_ok {
seek = 0
length_str := query.Get("length")
length, err = strconv.ParseInt(length_str, 10, 0)
if err != nil {
return responder.RespondWithError(ctx, http.StatusBadRequest, "length must be an integer value")
}
} else if !length_ok {
seek_str := query.Get("seek")
seek, err = strconv.ParseInt(seek_str, 10, 0)
if err != nil {
return responder.RespondWithError(ctx, http.StatusBadRequest, "seek must be an integer value")
}
length = n.File.Size - seek
} else {
seek_str := query.Get("seek")
seek, err = strconv.ParseInt(seek_str, 10, 0)
if err != nil {
return responder.RespondWithError(ctx, http.StatusBadRequest, "seek must be an integer value")
}
length_str := query.Get("length")
length, err = strconv.ParseInt(length_str, 10, 0)
if err != nil {
return responder.RespondWithError(ctx, http.StatusBadRequest, "length must be an integer value")
}
}
r, err := n.FileReader()
defer r.Close()
if err != nil {
err_msg := "[email protected]_Read:Open: " + err.Error()
logger.Error(err_msg)
return responder.RespondWithError(ctx, http.StatusInternalServerError, err_msg)
}
s := &request.Streamer{R: []file.SectionReader{}, W: ctx.HttpResponseWriter(), ContentType: "application/octet-stream", Filename: filename, Size: length, Filter: fFunc}
s.R = append(s.R, io.NewSectionReader(r, seek, length))
if download_raw {
err = s.StreamRaw()
if err != nil {
// causes "multiple response.WriteHeader calls" error but better than no response
err_msg := "err:@node_Read s.StreamRaw: " + err.Error()
logger.Error(err_msg)
return responder.RespondWithError(ctx, http.StatusBadRequest, err_msg)
}
} else {
err = s.Stream()
if err != nil {
// causes "multiple response.WriteHeader calls" error but better than no response
err_msg := "err:@node_Read s.Stream: " + err.Error()
logger.Error(err_msg)
return responder.RespondWithError(ctx, http.StatusBadRequest, err_msg)
}
}
} else if _, ok := query["index"]; ok {
//handling bam file
if query.Get("index") == "bai" {
if n.Type == "subset" {
return responder.RespondWithError(ctx, http.StatusBadRequest, "subset nodes do not support bam indices")
}
s := &request.Streamer{R: []file.SectionReader{}, W: ctx.HttpResponseWriter(), ContentType: "application/octet-stream", Filename: filename, Size: n.File.Size, Filter: fFunc}
var region string
if _, ok := query["region"]; ok {
//retrieve alingments overlapped with specified region
region = query.Get("region")
}
示例10: addResponseHeaders
func addResponseHeaders(ctx context.Context) {
ctx.HttpResponseWriter().Header().Set("Connection", "close")
ctx.HttpResponseWriter().Header().Set("Access-Control-Allow-Headers", "Authorization")
ctx.HttpResponseWriter().Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
ctx.HttpResponseWriter().Header().Set("Access-Control-Allow-Origin", "*")
}