PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How to install Gin with Golang

 August 24, 2022     go, go-gin, linux, module, webserver     No comments   

Issue

I'm a newbie on Golang, and I'm trying to use Gin to develop a web server on Ubuntu 16.04.

After executing go get -u github.com/gin-gonic/gin, many folders appear at ~/go/pkg/mod/github.com/.

Then I try to make an example:

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

However, go run example.go made the error:

example.go:3:8: cannot find package "github.com/gin-gonic/gin" in any of:
        /usr/local/go/src/github.com/gin-gonic/gin (from $GOROOT)
        /home/zyh/go/src/github.com/gin-gonic/gin (from $GOPATH)

In my system, $GOROOT is /usr/local/go/ and $GOPATH is ~/go/.

How could I solve this problem?


Solution

For Go version 1.11 or newer, You should use Go Modules.

If you are just starting with Go, you should start with the newer version. I think you are using a Go version that supports go modules already because the modules you are trying to get are downloading to ~/go/pkg/mod/ directory.

To initialize a project with go module, run:

go mod init your-project-name

This will create a go.mod file in your project directory.

Add missing and/or remove unused modules:

go mod tidy

This will fill up the go.mod file with appropriate modules and create a go.sum in your project directory. The go.sum contains expected cryptographic hashes of each module version.

After that, the go run example.go command should run the program without any issues.


You can even vendor the modules in your project directory:

go mod vendor

This will bring all the vendors to your projects /vendor directory so that you don't need to get the modules again if working from another machine on this project.



Answered By - aniskhan001
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing