-4

I want to start learning about the fasthttps server from this link https://github.com/valyala/fasthttp but I dont know that how will I implement a small piece of code in this framework. Can anybody tell me that how i will implement a small piece of code in this? example please.

Code I tried

package main

import "fmt"

type MyHandler struct {
    foobar string
}

func main() {

    // pass bound struct method to fasthttp
    myHandler := &MyHandler{
        foobar: "foobar",
    }
    fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP)

    // pass plain function to fasthttp
    fasthttp.ListenAndServe(":8081", fastHTTPHandler)
}

 // request handler in net/http style, i.e. method bound to MyHandler struct.
 func (h *MyHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) {
     // notice that we may access MyHandler properties here - see h.foobar.
     fmt.Fprintf(ctx, "Hello, world! Requested path is %q. Foobar is %q",
    ctx.Path(), h.foobar)
}

// request handler in fasthttp style, i.e. just plain function.
func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hi there! RequestURI is %q", ctx.RequestURI())
}

Can you please tell me that how I will implement this code.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
puneet55667788
  • 89
  • 2
  • 10
  • 4
    So, exactly in which point do you encounter a problem in your try? – vahdet Feb 13 '19 at 13:39
  • 3
    You didn't even import fasthttp. – leaf bebop Feb 13 '19 at 13:51
  • 4
    If you are new to Go the best advice might be: Just use net/http instead of something special with a very narrow focus. It will suit you better. – Volker Feb 13 '19 at 13:51
  • 1
    Asking for resources, such as examples, is off-topic here. If you have a specific problem, though, we can probably help with that. – Jonathan Hall Feb 13 '19 at 14:26
  • 3
    But first off: Don't use that library. If you're new to Go, first use the standard library's `net/http` package, and become very comfortable with that. Only then, and only if performance is not adequate, should you even begin to consider `fasthttp`. – Jonathan Hall Feb 13 '19 at 14:27

1 Answers1

3

This code seems to be working. I pasted it to a .go file, added:

import "github.com/valyala/fasthttp"

Then you have to install this package, either by using go get github.com/valyala/fasthttp or by writing a go.mod file if you want to use the new module support.

Then run this file and open localhost:8080 in a browser.


Maybe you have a more concrete question?

As @Volker said in a comment, for newbies it's highly recommended to stick to the standard library - net/http in this case; there are way more examples and code/tutorials you can find by googling, no need to install special packages, etc.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412