I am looking to split my routes.go into multiple files so that each group is in its own package. Can someone point me to an example of some code where someone has done this with Gin?
i.e.
package auth
...
auth = route.Group("/auth"){
auth.GET(...
auth.POST(...
}
...
package users
...
user = route.Group("/user"){
user.GET(...
user.POST(...
}
...
package main
import (
"auth"
"users"
)
...
router = gin.Default()
router.Register(auth.auth, users.user)
router.Run()
...
The way to do this is to create a function in each that takes a route as a parameter, and then adds the routes to the parameter:
package auth
import "...gin"
func Routes(route *gin.Engine)
auth := route.Group("/auth"){
auth.GET(...
auth.POST(...
}
...
package users
import "...gin"
func Routes(route *gin.Engine)
user := route.Group("/user"){
user.GET(...
user.POST(...
}
...
package main
import (
"github.com/username/package/sub/auth"
"github.com/username/package/sub/users"
"github.com/gin-gonic/gin"
)
...
router := gin.Default()
auth.Routes(router) //Added all auth routes
user.Routes(router) //Added all user routes
router.Run()
...
another example, different perspective... main group in main file, sub groups placed in different files in one directory groups
package groups
import "...gin"
func Customer(g *gin.RouterGroup) {
g.GET("/authorize", customer.Authorize)
g.POST("/register", customer.Register)
}
...
package groups
import "...gin"
func Info(g *gin.RouterGroup) {
g.GET("/car-color", controllers.CarColorsList)
g.GET("/car-type", controllers.CarTypesList)
g.GET("/car-manufacturer", controllers.CarManufacturersList)
g.GET("/car-model", controllers.CarModelsList)
}
...
package main
import (
"github.com/gin-gonic/gin"
"github.com/username/package/api/groups"
)
...
router := gin.Default()
v1 := router.Group("/v1")
{
v1.Use(AuthMiddleware)
groups.Info(v1.Group("/info"))
groups.Customer(v1.Group("/customer"))
}
router.Run()
...
Related
I'm creating an endpoint using Go's Gin web framework. I need full server URL in my handler function. For example, if server is running on http://localhost:8080 and my endpoint is /foo then I need http://localhost:8080/foo when my handler is called.
If anyone is familiar with Python's fast API, the Request object has a method url_for(<endpoint_name>) which has the exact same functionality: https://stackoverflow.com/a/63682957/5353128
In Go, I've tried accessing context.FullPath() but that only returns my endpoint /foo and not the full URL. Other than this, I can't find appropriate method in docs: https://pkg.go.dev/github.com/gin-gonic/gin#Context
So is this possible via gin.Context object itself or are there other ways as well? I'm completely new to Go.
c.Request.Host+c.Request.URL.Path should work but the scheme has to be determined.
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/foo", func(c *gin.Context) {
fmt.Println("The URL: ", c.Request.Host+c.Request.URL.Path)
})
r.Run(":8080")
}
You can determine scheme which also you may know already. But you can check as follows:
scheme := "http"
if c.Request.TLS != nil {
scheme = "https"
}
If your server is behind the proxy, you can get the scheme by c.Request.Header.Get("X-Forwarded-Proto")
You can get host part localhost:8080 from context.Request.Host and path part /foo from context.Request.URL.String().
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/foo", func(c *gin.Context) {
c.String(http.StatusOK, "bar")
fmt.Println(c.Request.Host+c.Request.URL.String())
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
And you can get http protocol version by context.Request.Proto, But it will not determine http or https. you need to get it from your service specifications.
This is newbie question. The dependencies seems to be on github, and it's pretty obvious from the import, so why run doesn't work?
Error is: no required module provides package github.com/hashicorp/go-getter
package main
import (
"context"
"fmt"
"os"
// Problem with line below, getting error: no required module provides package
getter "github.com/hashicorp/go-getter"
)
func main() {
client := &getter.Client{
Ctx: context.Background(),
//define the destination to where the directory will be stored. This will create the directory if it doesnt exist
Dst: "/tmp/gogetter",
Dir: true,
//the repository with a subdirectory I would like to clone only
Src: "github.com/hashicorp/terraform/examples/cross-provider",
Mode: getter.ClientModeDir,
//define the type of detectors go getter should use, in this case only github is needed
Detectors: []getter.Detector{
&getter.GitHubDetector{},
},
//provide the getter needed to download the files
Getters: map[string]getter.Getter{
"git": &getter.GitGetter{},
},
}
//download the files
if err := client.Get(); err != nil {
fmt.Fprintf(os.Stderr, "Error getting path %s: %v", client.Src, err)
os.Exit(1)
}
//now you should check your temp directory for the files to see if they exist
}
Create a folder somewhere called getter, then create a file
getter/getter.go:
package main
import (
"fmt"
"github.com/hashicorp/go-getter/v2"
)
func main() {
fmt.Println(getter.ErrUnauthorized)
}
Notice I didn't use a name like you specified, as it's redundant in this case. The package is already called getter [1], so you don't need to specify the same name. Then, run:
go mod init getter
go mod tidy
go build
https://pkg.go.dev/github.com/hashicorp/go-getter/v2
I am trying to build a web app with two files.
app.go and main.go are both in the same directory.
app.go
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (a *App) Initialize(username, password, server, port, dbName, cacheAddr, cachePass string){
}
func (a *App) Run(addr string) {
}
main.go
package main
func main() {
a := App{}
// more code here
}
I thought my main.go file would recognize App{} but my editor is complaining that App is undeclared name
Both files are in the same main package but I am not sure what went wrong. Could anyone help me about it? Thank you!
From the comments I assume you run the following command: go run main.go. This will ONLY load code in main.go (and files included with import statements). To tell Go to load all .go files in the current directory, run the following instead:
go run .
Similarly, to tell VSCode to load alll files start it like this:
code .
I saw the similar question here. But I couldn't solve my case.
I am having project initialised with dep and added the first dependency "Echo". Now folder structure looks like this
|--server
| |--server.go
|--vendor
|--main.go
The server.go has the following code
package server
import (
"net/http"
"github.com/labstack/echo"
)
// TestController : Test controller
func TestController(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}
and the main.go has
package main
import (
"github.com/labstack/echo"
"github.com/sfkshan/pos/server"
)
func main() {
e := echo.New()
e.GET("/", server.TestController)
e.Logger.Fatal(e.Start(":1323"))
}
Now vscode shows the warning
cannot use server.TestController (type
func("github.com/sfkshan/pos/vendor/github.com/labstack/echo".Context)
error) as type "github.com/labstack/echo".HandlerFunc in argument to
e.GET
I am not sure why is this happening? If I delete the vendor folder folder the error vanishes. But again after running dep ensure (in this case vendor folder gets created which is expected) the error appears again.
I'm writing a small web app with gorilla/mux. My folder structure inside my GOPATH is like this.
app/
- app.go
- views/
- layout.html
- login/
- login.go
- login_test.go
- login.html
I'd like to keep login as a completely separate package. Within login.go I initiate the template and render it on request. All file paths are relative to app.go as I run go run app.go in my main app/ folder.
package login
var view = template.Must(template.ParseFiles(
"login/login.html",
"views/layout.html",
))
func GetLogin(w http.ResponseWriter, r *http.Request) {
err := view.ExecuteTemplate(w, "layout", nil)
check(err)
}
That works fine and I can call the route in my app.go file.
import (
"github.com/zemirco/app/login"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", login.GetLogin).Methods("GET")
http.Handle("/", router)
http.ListenAndServe(":"+os.Getenv("PORT"), nil)
}
My problem is testing this route. Within login_test.go I have something like this.
package login
import (
"net/http"
"net/http/httptest"
"testing"
"."
)
func TestHandleGetLogin(t *testing.T) {
request, _ := http.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
login.GetLogin(response, request)
t.Log(response)
}
Whenever I run go test login/login_test.go I get the error message
open login/login.html: no such file or directory
As far as I know go test executes from within the login/ directory and therefore cannot find the html files. The relative file paths are wrong.
How can I solve this problem or what would be a better directory structure?