I have deployed the Go App on Heroku but on hitting the url.. its not giving proper response. The Heroku logs looks something like this :
2015-06-27T10:43:06.839094+00:00 heroku[web.1]: Starting process with command `FlickrImage`
2015-06-27T10:43:08.998400+00:00 heroku[web.1]: State changed from starting to crashed
2015-06-27T10:43:08.998400+00:00 heroku[web.1]: State changed from crashed to starting
2015-06-27T10:43:08.985737+00:00 heroku[web.1]: Process exited with status 0
2015-06-27T10:43:10.795684+00:00 heroku[web.1]: Starting process with command `FlickrImage`
2015-06-27T10:43:13.837301+00:00 heroku[web.1]: Process exited with status 0
2015-06-27T10:43:13.850141+00:00 heroku[web.1]: State changed from starting to crashed
2015-06-27T10:44:41.914412+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/Index" host=morning-ridge-1365.herokuapp.com request_id=89d2e794-a725-4ddf-b437-dbcbd988428c fwd="202.12.83.44" dyno= connect= service= status=503 bytes=
FlickrImage is my go file and I have created a Procfile which contains "web: FlickrImage"
EDIT :
FlickrImageServer Code :
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type imageLinks struct {
Link string `bson:"link"`
Upvote int `bson:"upvote"`
Downvote int `bson:"downvote"`
}
type Result struct {
Photos struct {
Page int `json: "page"`
Pages int `json: "pages"`
PerPage int `json: "perpage"`
Total string `json: "total"`
Photo []struct {
Id string `json: "id"`
Owner string `json: "owner"`
Secret string `json: "secret"`
Server string `json: "server"`
Farm int `json: "farm"`
Title string `json: "title"`
IsPublic int `json: "ispublic"`
IsFriend int `json: "isfriend"`
IsFamily int `json: "isfamily`
} `json: "photo"`
} `json: "photos"`
Stat string `json: "stat"`
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/Index", Index)
router.HandleFunc("/UpVote", UpVoteRoute)
router.HandleFunc("/DownVote", DownVoteRoute)
log.Fatal(http.ListenAndServe(":8080", router))
}
func UpVoteRoute(w http.ResponseWriter, r *http.Request) {
link := r.URL.Query().Get("imagelink")
w.Header().Set("Content-Type", "application/json")
session, err := mgo.Dial("mongodb://<user>:<password>#ds061631.mongolab.com:61631/flickrimagedb")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("flickrimagedb").C("image_links_votes")
err = c.Update(bson.M{"link": link}, bson.M{"$inc": bson.M{"upvote": 1}})
if err != nil {
fmt.Printf("Can't update document %v\n", err)
os.Exit(1)
}
}
func DownVoteRoute(w http.ResponseWriter, r *http.Request) {
link := r.URL.Query().Get("imagelink")
w.Header().Set("Content-Type", "application/json")
session, err := mgo.Dial("mongodb://*********:*******#ds061631.mongolab.com:61631/flickrimagedb")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("flickrimagedb").C("image_links_votes")
err = c.Update(bson.M{"link": link}, bson.M{"$inc": bson.M{"downvote": 1}})
if err != nil {
fmt.Printf("Can't update document %v\n", err)
os.Exit(1)
}
}
func Index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
session, err := mgo.Dial("mongodb://*********:*********#ds061631.mongolab.com:61631/flickrimagedb")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("flickrimagedb").C("image_links_votes")
checkResult := &imageLinks{}
// Create a slice to begin with
myType := reflect.TypeOf(checkResult)
slice := reflect.MakeSlice(reflect.SliceOf(myType), 10, 10)
// Create a pointer to a slice value and set it to the slice
x := reflect.New(slice.Type())
x.Elem().Set(slice)
err = c.Find(bson.M{}).All(x.Interface())
if err != nil {
response, err := json.Marshal(x.Interface())
if err != nil {
fmt.Printf("%s", err)
os.Exit(2)
}
fmt.Fprintf(w, string(response))
} else {
url := "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=*****************************&text=cute+puppies&per_page=12&format=json&nojsoncallback=1"
res, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
os.Exit(3)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(4)
}
jsonData := &Result{}
err = json.Unmarshal(body, jsonData)
for value := range jsonData.Photos.Photo {
s1 := []string{"https://farm", ".staticflickr.com/"}
s2 := []string{strings.Join(s1, strconv.Itoa(jsonData.Photos.Photo[value].Farm)), "/"}
s3 := []string{strings.Join(s2, jsonData.Photos.Photo[value].Server), "_"}
s4 := []string{strings.Join(s3, jsonData.Photos.Photo[value].Id), ".jpg"}
s := strings.Join(s4, jsonData.Photos.Photo[value].Secret)
singleReuslt := imageLinks{}
err = c.Find(bson.M{"link": s}).One(&singleReuslt)
if err != nil {
err = c.Insert(&imageLinks{Link: s, Upvote: 0, Downvote: 0})
if err != nil {
fmt.Printf("%s", err)
os.Exit(5)
}
}
}
allResult := &imageLinks{}
// Create a slice to begin with
myType := reflect.TypeOf(allResult)
slice := reflect.MakeSlice(reflect.SliceOf(myType), 10, 10)
// Create a pointer to a slice value and set it to the slice
x := reflect.New(slice.Type())
x.Elem().Set(slice)
err = c.Find(bson.M{}).All(x.Interface())
response, err := json.Marshal(x.Interface())
if err != nil {
fmt.Printf("%s", err)
os.Exit(6)
}
fmt.Fprintf(w, string(response))
}
}
Any help would be appreciated
Heroku dynos dynamically assign a port. It's likely your application is crashing because it can't bind to port 8080.
Change this line:
log.Fatal(http.ListenAndServe(":8080", router))
... to this:
port := ":" + os.Getenv("PORT")
log.Fatal(http.ListenAndServe(port, router))
Related
How to chromedp pdf download without saving in server?
Below code is working for generating pdf file and saving in server side. But I want to download pdf file without saving in server side.
func PDFInvoice(c *gin.Context) {
session := sessions.Default(c)
id := c.Params.ByName("id")
token := session.Get("login_session").(string)
// create context
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// capture pdf
var buf []byte
url := "http://localhost:8080/invoice/" + id + "/" + token
if err := chromedp.Run(ctx, printToPDF(url, &buf)); err != nil {
log.Fatal(err)
}
buff := new(bytes.Buffer)
if _, err := buff.WriteTo(c.Writer); err != nil {
panic(err)
}
if err := os.WriteFile("sample.pdf", buf, 0o644); err != nil {
log.Fatal(err)
}
//ioutil.WriteFile("sample.pdf", buf, 0644)
c.JSON(200, id+" "+token)
}
// print a specific pdf page.
func printToPDF(urlstr string, res *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(urlstr),
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().WithPrintBackground(false).Do(ctx)
if err != nil {
return err
}
*res = buf
return nil
}),
}
}
You can write the bytes to http.ResponseWriter directly. See the demo below:
package main
import (
"context"
"log"
"net/http"
"sync"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func main() {
http.Handle("/pdf", http.HandlerFunc(servePDF))
log.Fatal(http.ListenAndServe(":8080", http.DefaultServeMux))
}
func servePDF(w http.ResponseWriter, r *http.Request) {
buf, err := createPDF()
if err != nil {
log.Fatalln(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/pdf")
w.Write(buf)
}
func createPDF() ([]byte, error) {
ctx, cancel := newTabContext()
defer cancel()
html := `<html>
<body>
<div>text</div>
<img src="https://pkg.go.dev/static/shared/gopher/package-search-700x300.jpeg"/>
<img src="https://go.dev/images/gophers/motorcycle.svg"/>
<img src="https://go.dev/images/go_google_case_study_carousel.png" />
</body>
</html>`
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Navigate("about:blank"),
// set the page content and wait until the page is loaded (including its resources).
chromedp.ActionFunc(func(ctx context.Context) error {
lctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
wg.Add(1)
chromedp.ListenTarget(lctx, func(ev interface{}) {
if _, ok := ev.(*page.EventLoadEventFired); ok {
// It's a good habit to remove the event listener if we don't need it anymore.
cancel()
wg.Done()
}
})
frameTree, err := page.GetFrameTree().Do(ctx)
if err != nil {
return err
}
if err := page.SetDocumentContent(frameTree.Frame.ID, html).Do(ctx); err != nil {
return err
}
wg.Wait()
return nil
}),
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
buf, _, err = page.PrintToPDF().WithPrintBackground(false).Do(ctx)
if err != nil {
return err
}
return nil
}),
); err != nil {
return nil, err
}
return buf, nil
}
var (
browserCtx context.Context
once sync.Once
)
// newTabContext creates a tab context with the global browser context as its parent context.
//
// When tasks is run with the returned context, a new tab will be created in the browser.
func newTabContext() (context.Context, context.CancelFunc) {
once.Do(func() { initBrowser() })
if browserCtx == nil || browserCtx.Err() != nil {
log.Fatalf("browser is not available: %v", browserCtx.Err())
}
return chromedp.NewContext(browserCtx)
}
// initBrowser starts a browser in which to create new tab for running tasks.
func initBrowser() {
browserCtx, _ = chromedp.NewContext(context.Background())
// to start the browser
if err := chromedp.Run(browserCtx); err != nil {
log.Fatal(err)
}
}
Usage:
go run main.go
curl http://localhost:8080/pdf > sample.pdf
References:
https://github.com/chromedp/chromedp/issues/941
https://github.com/chromedp/chromedp/issues/836
I need help with Golang websocket. I'm using Fiber with websocket and redis.
Here is the code:
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/go-redis/redis/v8"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
"log"
"test4/controllers"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
var ctx = context.Background()
var redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
func TestSocket() fiber.Handler {
socket := websocket.New(func(c *websocket.Conn) {
go deliverMessages(c)
var (
msg []byte
err error
)
for {
if _, msg, err = c.ReadMessage(); err != nil {
log.Println("read:", err)
break
}
if err := redisClient.Publish(ctx, "chat", msg).Err(); err != nil {
log.Println("publish:", err)
break
}
}
})
return socket
}
func deliverMessages(c *websocket.Conn) {
subscriber := redisClient.Subscribe(ctx, "chat")
user := User{}
for {
msg, err := subscriber.ReceiveMessage(ctx)
if err != nil {
log.Println("subscriber:", err)
panic(err)
}
if err := json.Unmarshal([]byte(msg.Payload), &user); err != nil {
log.Println("Unmarshal:", err)
panic(err)
}
text := []byte(fmt.Sprintf("{\"name\":\"%s\", \"email\":\"%s\"}", user.Name, user.Email))
if err = c.WriteMessage(websocket.TextMessage, text); err != nil {
log.Println("write:", err)
break
}
}
}
func main() {
app := fiber.New(fiber.Config{
Prefork: true,
CaseSensitive: true,
StrictRouting: true,
DisableStartupMessage: true,
ServerHeader: "Test v3",
})
app.Get("/", controllers.Home)
app.Get("/ws", TestSocket())
log.Fatal(app.Listen("0.0.0.0:3000"))
}
How to produce the error:
Install Redis and run go run main.go
Now open http://127.0.0.1:3000/ in two tabs
click open on both tabs, and then you will see OPEN on right side of browser
click send on both tabs and you will get SEND and RESPONSE
Now close one tab and on go program terminal you will see error (see attached screenshot)
Now publish data to chat channel on redis-cli
Here is the error I am getting:
I think this is nil pointer websocket.Conn issue.
When close websocket connection, goroutine's c *websocket.Conn is loose data.
Pointer point nil.
solution
use channel, use local redisClient var
func TestSocket() fiber.Handler {
socket := websocket.New(func(c *websocket.Conn) {
var redisClient = redis.NewClient(&redis.Options{ // <-- use local redisClient var
Addr: "localhost:6379",
})
go deliverMessages(c)
var (
msg []byte
err error
)
defer func() {
redisClient.Close() // <-- then close, when websocket connection close
quitSubscribeGoRutine <- true // <-- change true, when websocket connection close
}()
for {
if _, msg, err = c.ReadMessage(); err != nil {
log.Println("read:", err)
...
func deliverMessages(c *websocket.Conn) {
subscriber := redisClient.Subscribe(ctx, "chat")
user := User{}
for {
select {
case <-quitSubscribeGoRutine: // <-- exit goroutine, when channel is true
return
default:
msg, err := subscriber.ReceiveMessage(ctx) // <-- exit goroutine, when redisClient close
if err != nil {
log.Println("subscriber:", err)
break // <-- use break instead of panic
}
if err := json.Unmarshal([]byte(msg.Payload), &user); err != nil {
log.Println("Unmarshal:", err)
panic(err)
}
text := []byte(fmt.Sprintf("{\"name\":\"%s\", \"email\":\"%s\"}", user.Name, user.Email))
if err = c.WriteMessage(websocket.TextMessage, text); err != nil {
log.Println("write:", err)
break
}
}
}
}
I am trying to send a raw transaction with eth.sendTransaction but I am getting an error that says {"code":-32000,"message":"unknown account"}. I am not sure what is causing this and I cant seem to find an answer on the internet. Can anyone help me figure it out? Here is my code:
func ExecuteSignedTransaction(rawTransaction string) {
var hash web3.Hash
data := make(map[string]interface{})
data["data"] = rawTransaction
err := Web3HTTPClient.Call("eth_sendTransaction", &hash, data)
if err != nil{
fmt.Println(err)
Os.Exit(1)
}
fmt.Println("Sent tx hash:", hash)
}
So, what I might do here:
import (
"strings"
"crypto/ecdsa"
"math/big"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
)
var chainId = big.NewInt(1) // chain id for the ethereum mainnet, change according to needs
func ecdsaPrivateKeyFromHex(privKeyHex string) *ecdsa.PrivateKey {
ecdsaKey, err := crypto.HexToECDSA(privKeyHex)
if err != nil { panic(err) }
return ecdsaKey
}
func newTransactOpts(privKey *ecdsa.PrivateKey) *bind.TransactOpts {
transactOpts, err := bind.NewKeyedTransactorWithChainID(privKey, chainId)
if err != nil { panic(err) }
return transactOpts
}
func newRpcClient() *ethclient.Client {
c, err := ethclient.Dial("insert rpc url here")
if err != nil { panic(err) }
return c
}
// note: constructing the *types.Transaction object left as
// an exercise to the reader
func ExecuteTransaction(rawTransaction *types.Transaction) {
privKeyHex := "0xblahblahblahblahblah" // use your own account's private key
transactOpts := newTransactOpts(ecdsaPrivateKeyFromHex(privKeyHex))
signedTxn, err := transactOpts.Signer(transactOpts.From, rawTransaction)
if err != nil { panic(err) }
rpcClient := newRpcClient()
if err := rpcClient.SendTransaction(context.Background(), signedTxn); err != nil { panic(err) }
// do whatever
}
Hope everyone is having a good week. I’m trying to get my code to prompt a user to enter their password. as of right now if you run the code and do --help you get a few flag parameters. So I don’t want the user to show their password via the terminal prompt. Basically give the pram and fire the code and enter password. I hope I explained it right, on what I’m trying to do. I’m still green in Go. example:
-ipAddress string ip address of the managed server to be added
-password string hmc user password
-url string hmc REST api url
-user string hmc user
package main
import (
"bytes"
"crypto/tls"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"text/template"
"golang.org/x/crypto/ssh/terminal"
)
//
// XML parsing structures
//
type Feed struct {
Entry struct {
Content struct {
ManagementConsole struct {
Metadata struct {
Atom struct {
AtomID string `xml:"AtomID"`
AtomCreated string `xml:"AtomCreated"`
} `xml:"Atom"`
} `xml:"Metadata"`
} `xml:"ManagementConsole"`
} `xml:"content"`
} `xml:"entry"`
}
// HTTP session struct
//
type Session struct {
client *http.Client
User string
Password string
url string
}
type Manage struct {
Ipaddress string
}
func NewSession(user string, password string, url string) *Session {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
return &Session{client: &http.Client{Transport: tr, Jar: jar}, User: user, Password: password, url: url}
}
func (s *Session) doLogon() {
authurl := s.url + "/rest/api/web/Logon"
// template for login request
logintemplate := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<LogonRequest xmlns="http://www.ibm.com/xmlns/systems/power/firmware/web/mc/2012_10/" schemaVersion="V1_1_0">
<Metadata>
<Atom/>
</Metadata>
<UserID kb="CUR" kxe="false">{{.User}}</UserID>
<Password kb="CUR" kxe="false">{{.Password}}</Password>
</LogonRequest>`
tmpl := template.New("logintemplate")
tmpl.Parse(logintemplate)
authrequest := new(bytes.Buffer)
err := tmpl.Execute(authrequest, s)
if err != nil {
log.Fatal(err)
}
request, err := http.NewRequest("PUT", authurl, authrequest)
// set request headers
request.Header.Set("Content-Type", "application/vnd.ibm.powervm.web+xml; type=LogonRequest")
request.Header.Set("Accept", "application/vnd.ibm.powervm.web+xml; type=LogonResponse")
request.Header.Set("X-Audit-Memento", "hmctest")
response, err := s.client.Do(request)
fmt.Println("\n")
fmt.Println(response)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
if response.StatusCode != 200 {
log.Fatalf("Error status code: %d", response.StatusCode)
}
}
}
func (s *Session) getManaged()(string) {
hmcUUID :=""
// mgdurl := s.url + "/rest/api/uom/LogicalPartition"
mgdurl := s.url + "/rest/api/uom/ManagementConsole"
request, err := http.NewRequest("GET", mgdurl, nil)
request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
response, err := s.client.Do(request)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
if response.StatusCode != 200 {
log.Fatalf("Error getting LPAR informations. status code: %d", response.StatusCode)
}
var feed Feed
new_err := xml.Unmarshal(contents, &feed)
if new_err != nil {
log.Fatal(new_err)
}
fmt.Printf("AtomID: %v\n", feed.Entry.Content.ManagementConsole.Metadata.Atom.AtomID)
fmt.Printf("AtomCreated: %v\n", feed.Entry.Content.ManagementConsole.Metadata.Atom.AtomCreated)
hmcUUID = feed.Entry.Content.ManagementConsole.Metadata.Atom.AtomID
}
return hmcUUID
}
func (s *Session) addManaged(uuid *string, i *Manage){
addManagedURl := s.url + "/rest/api/uom/ManagementConsole/" + *uuid + "/do/AddManagedSystem"
addManagedTemplate := `<JobRequest:JobRequest
xmlns:JobRequest="http://www.ibm.com/xmlns/systems/power/firmware/web/mc/2012_10/"
xmlns="http://www.ibm.com/xmlns/systems/power/firmware/web/mc/2012_10/"
xmlns:ns2="http://www.w3.org/XML/1998/namespace/k2" schemaVersion="V1_0">
<Metadata>
<Atom/>
</Metadata>
<RequestedOperation kb="CUR" kxe="false" schemaVersion="V1_0">
<Metadata>
<Atom/>
</Metadata>
<OperationName kb="ROR" kxe="false">AddManagedSystem</OperationName>
<GroupName kb="ROR" kxe="false">ManagementConsole</GroupName>
</RequestedOperation>
<JobParameters kb="CUR" kxe="false" schemaVersion="V1_0">
<Metadata>
<Atom/>
</Metadata>
<JobParameter schemaVersion="V1_0"><Metadata><Atom/></Metadata>
<ParameterName kb="ROR" kxe="false">host</ParameterName>
<ParameterValue kb="CUR" kxe="false">{{.Ipaddress}}</ParameterValue>
</JobParameter>
<JobParameter schemaVersion="V1_0"><Metadata><Atom/></Metadata>
<ParameterName kb="ROR" kxe="false">password</ParameterName>
<ParameterValue kb="CUR" kxe="false">abcc123</ParameterValue>
</JobParameter>
</JobParameters>
</JobRequest:JobRequest> `
tmpl := template.New("addManagedTemplate")
tmpl.Parse(addManagedTemplate)
addrequest := new(bytes.Buffer)
err := tmpl.Execute(addrequest, i)
if err != nil {
log.Fatal(err)
}
request, err := http.NewRequest("PUT", addManagedURl, addrequest)
// set request headers
request.Header.Set("Content-Type", "application/vnd.ibm.powervm.web+xml; type=JobRequest")
request.Header.Set("Accept", "application/atom+xml; charset=UTF-8")
// request.Header.Set("Expect", "")
response, err := s.client.Do(request)
fmt.Println("\n")
fmt.Println(response)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
if response.StatusCode != 200 {
log.Fatalf("Error status code: %d", response.StatusCode)
}
}
}
func readPassword(prompt string) string {
fmt.Print(prompt)
pass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
panic(err)
}
println()
return string(pass)
}
func main() {
// Variables
password := readPassword("hmc Password: ")
//confirm := readPassword("Confirm hmc Password: ")
user := flag.String("user", "", "hmc user")
password := flag.String("password", "", "hmc user password")
url := flag.String("url", "", "hmc REST api url")
ipAddress := flag.String("ipAddress", "", "ip address of the managed server to be added")
flag.Parse()
//initialize new http session
fmt.Printf("server %s is being added.../n", *ipAddress)
session := NewSession(*user, *password, *url)
//var password string = readPassword("hmc password")
session.doLogon()
hmcUUID := session.getManaged()
ipaddr := &Manage {
Ipaddress: *ipAddress,
}
session.addManaged(&hmcUUID, ipaddr)
fmt.Println(hmcUUID)
}
Have a look at golang.org/x/crypto/ssh/terminal.
You can do something like this:
import (
"bufio"
"bytes"
"fmt"
"os"
"sync"
"syscall"
"golang.org/x/crypto/ssh/terminal"
)
func ReadPass() (password *bytes.Buffer, err error) {
var fi, _ = os.Stdin.Stat()
var pass []byte
isChardev := fi.Mode()&os.ModeCharDevice != 0
isNamedPipe := fi.Mode()&os.ModeNamedPipe != 0
if ! isChardev || isNamedPipe {
sin := bufio.NewReader(os.Stdin)
pass, _, err = sin.ReadLine()
} else {
_, _ = os.Stderr.WriteString(fmt.Sprint("passphrase: "))
pass, err = terminal.ReadPassword(syscall.Stdin)
if err != nil {
return nil, err
}
defer fmt.Println()
}
return bytes.NewBuffer(pass), err
}
The above example is taken from here:
https://github.com/tox2ik/go-smux/blob/master/io/terminal.go
I am new in Golang and I am trying to store image in the files on server and save its directory in MySQL Database. The code is running fine the DB is also storing the directory of the stored image correctly but the output json is showing the directory not correctly and I am not able to solve this. If also possible I want to give proper name to the saved file while creating and storing the image in the directory.I know should use jpeg or png but don't know how to set directory for these. The Directory has a parent folder profile-pic and child folder created from the mobile number I get form the POST Request where the image is stored. The Code is given below main.go
func main() {
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
for _, addr := range addrs {
if ipv4 := addr.To4(); ipv4 != nil {
fmt.Println("IPv4: ", ipv4)
}
}
r := httprouter.New()
uc := controller.NewUserController(getSession())
r.GET("/", uc.Starter)
r.POST("/create", uc.MobileCreate)
http.ListenAndServe(":8080", r)
}
func getSession() *sql.DB {
s, err := sql.Open("mysql", "root:password#tcp(127.0.0.1:3306)/test")
if err != nil {
panic(err)
}
return s
}
controller.go
type UserController struct {
session *sql.DB
}
func NewUserController(s *sql.DB) *UserController {
return &UserController{s}
}
func (uc UserController) Starter(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `Your at homepage and Connection to db was success and check the terminal for dump diagnosis!`)
fmt.Println("Request Dump:\n", string(dump))
}
func (uc UserController) MobileCreate(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
r.ParseMultipartForm(10 << 20)
UserName := r.FormValue("name")
EmailId := r.FormValue("email")
PassWord := r.FormValue("password")
MobileNumber := r.FormValue("mobile")
i, _ := strconv.ParseInt(MobileNumber, 0, 64)
AddRess := r.FormValue("address")
ProfilePic, _, err := r.FormFile("profilePic")
DirectoryName := "profile-pics" + "\\" + MobileNumber
_ = DirectoryName + "\\" + "dp.png"
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer ProfilePic.Close()
_, err = os.Stat("test")
if os.IsNotExist(err) {
errDir := os.MkdirAll("profile-pics"+"\\"+MobileNumber, 0755)
if errDir != nil {
log.Fatal(err)
}
}
tempFile, err := ioutil.TempFile("profile-pics"+"\\"+MobileNumber, "*.png")
if err != nil {
fmt.Println(err)
}
defer tempFile.Close()
fileBytes, err := ioutil.ReadAll(ProfilePic)
if err != nil {
fmt.Println(err)
}
// write this byte array to our temporary file
tempFile.Write(fileBytes)
u := models.User{
Name: UserName,
Email: EmailId,
Password: PassWord,
Mobile: i,
Address: AddRess,
ProfilePic: tempFile.Name(),
}
query, err := uc.session.Prepare("Insert loggedin SET name=?, email=?,pwd=?,number=?,address=?,profilepic=?")
if err != nil {
panic(err)
}
_, err = query.Exec(u.Name, u.Email, u.Password, u.Mobile, u.Address, u.ProfilePic)
if err != nil {
panic(err)
}
defer query.Close()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) // 201
err = json.NewEncoder(w).Encode(u)
if err != nil {
fmt.Println(err)
}
}
model/user.go
type User struct {
Name string `json:"name" `
Email string `json:"email" `
Password string `json:"password" `
Mobile int64 `json:"mobile" `
Address string `json:"address" `
ProfilePic string `json: image`
}
The entry in database is correct
The json Output
"profile-pics\\9041111113\\103561439.png"
I tried naming the img to dp but the img was then saved in unsupported format
I want to remove double \\because i have to load this image in android app with picasso lib and it doesn't convert \\ to single \
Picasso.get()
.load(json output as string)
.into(imageView)
I want to save the image in png only.