Does gin-gonic support get request? - go

I am new in gin-gonic framework and i have been trying to read the values from the inputs that i added in a get request from html but i have not been able to read the values that i wrote.
When i submit the request the browser sends this url :
http://localhost:3000/backend?name1=value1&name2=value2&name3=value3
I have been looking in the internet where gin-gonic uses this url type but i have only found that it uses url like this one
http://localhost:3000/backend/value1
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="GET" action="/backend">
<input id="store" name="name1" type="text">
<input id="razon" name="name2" type="text">
<input id="total" name="name3" type="text">
<input type="submit" value="submit">
</form>
</body>
</html>
golang code:
package main
import(
"net/http"
"fmt"
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
)
func main(){
router := gin.Default()
router.Use(static.Serve("/",static.LocalFile("./views",true)))
router.GET("/backend",func(c *gin.Context){
fmt.Println(c.Param("name1"))
c.JSON(http.StatusOK, gin.H{
"name1" : c.Param("name1"),
})
})
router.Run(":3000")
}
Actual result:
{"name1":""}
Expected result:
{"name1":"value1"}

The function you are looking for is not Param(), it's Query().
https://github.com/gin-gonic/gin#querystring-parameters

Related

How to Golang loop in html with http/template and net/http?

I am trying to handle data and then send it into html to be displayed in a specific field.
No expected output into {{.name}}. Works fine with {{.}}. No known structural wrongdoing.
Golang code
package main
import (
"fmt"
"html/template"
"net/http"
"github.com/gorilla/context"
)
var tpl *template.Template
func main() {
tpl, _ = template.ParseGlob("*.html")
http.HandleFunc("/test", testHandler)
http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
}
type Data struct {
allData []string
}
func testHandler(w http.ResponseWriter, r *http.Request) {
data := Data{allData: []string{"Add new", "jeff", "ffeej"}}
tpl.ExecuteTemplate(w, "test.html", data)
}
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<section>
{{range .allData}}
{{.}}
{{end}}
</section>
</body>
</html>
How does one get the data out of the handler into the html in a specific wanted field?
What am I missing? I am still learning golang.
Thanks in advance.

How to use Stripe Element Into Laravel Blade

I have a Laravel project. I want to add Stripe payment system in my Laravel app. In stripe there is js Element but unfortunately I cannot use it in blade files. Can anyody help me suggest other way to do this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stripe Payment</title>
</head>
<body>
<!-- Mount the instance within a <label> -->
<label>Card
<div id="card-element"></div>
</label>
<!--
Or create a <label> with a 'for' attribute,
referencing the ID of your container.
-->
<label for="card-element">Card</label>
<div id="card-element"></div>
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('pk_test_....');
const elements = stripe.elements();
const cardElement = elements.create("payment", {"clientSecret": "sk_test_...."});
cardElement.mount('#card-element');
</script>
</body>
</html>

Spring-MVC Thymeleaf from not submitting

I'm new to spring and I've tried coding a prototype.
I've tried making a form. Whenever I press the submit-button, nothing happens.
I'm using Spring Boot 2.4.3 with Oracle OpenJDK 15.0.2. I've tried Firefox and Chrome. The js-console is empty.
This is my model (Patient.java):
public class Patient implements Serializable {
private long id;
private String firstname;
private String lastname;
// Geters and seters
}
My Controller (PatientController.java):
#Controller
public class PatientController {
#GetMapping("/patient")
public String patientForm(Model model) {
model.addAttribute("patient", new Patient());
return "addPatient";
}
#PostMapping("/patient")
public String patientSubmit(#ModelAttribute("patient") Patient patient, Model model) {
model.addAttribute("patient", patient);
return "addedPatient";
}
}
My addPatient.html:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<from action="#" th:action="#{/patient}" th:object="${patient}" method="post">
<p>Id: <input type="number" th:field="*{id}"/></p>
<p>Firstname: <input type="text" th:field="*{firstname}"/></p>
<p>Lastname : <input type="text" th:field="*{lastname}"/></p>
<button type="submit">Register</button>
</from>
</body>
</html>
My addedPatient.html:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<p th:text="'Added ' + '[' + ${patient.id} + ']' + ${patient.firstname} + ' ' + ${patient.lastname}"></p>
Add another patient
</body>
</html>
The from tag on the addPatient.hmtl page is wrong, if you change it to form tag as below, the problem is solved:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<form action="#" th:action="#{/patient}" th:object="${patient}" method="post">
<p>Id: <input type="number" th:field="*{id}"/></p>
<p>Firstname: <input type="text" th:field="*{firstname}"/></p>
<p>Lastname : <input type="text" th:field="*{lastname}"/></p>
<button type="submit">Register</button>
</form>
</body>
</html>

hashing image with watermark in laravel

i use in my project image package Intervention-Image
to add watermark to every uploaded image in serve i use code blow but have error in hashing
hashing give me the hash of watermark.png only every time
Route::post('/upload_image',function (Request $request)
{
$real_path = Image::make($request->file('image')->getRealPath());
$img_for_hash = Image::make($real_path);
$img = Image::make($real_path);
// calculate md5 hash of encoded image
$hash = md5($img_for_hash->__toString());
// use hash as a name
$path = "images/{$hash }.jpg";
$watermark = Image::make(public_path('watermark.png'));
$img->insert($watermark, 'bottom-right', 10, 10);
// save it locally to ~/public/images/{$hash}.jpg
$img->save(public_path($path));
return $hash ;
})->name('upload_image');
view
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Upload Image</title>
</head>
<body>
<form action="{{ route('upload_image') }}" method="post" enctype="multipart/form-data" >
#csrf
<input type="file" name="image">
<button type="submit"> upload </button>
</form>
</body>
</html>
are any solution use call back or this because watermark ?? i don't know why this code give me same hash every time .

Golang template does not render html

I created a subfolder called 'views' in my web root directory. Within the View folder, I have the static folder which contains the css and js files.
The html pages are rendered when I have the html files in the web root. However they do not render when placed within the views folder. I am using template.ParseGlob to parse the file and ExecuteTemplate to render.
package main
import (
"html/template"
"net/http"
"github.com/gorilla/mux"
)
var router = mux.NewRouter()
var tmpl *template.Template
func init() {
tmpl = template.Must(template.ParseGlob("view/*.html"))
}
func indexPage(w http.ResponseWriter, r *http.Request) {
err := tmpl.ExecuteTemplate(w, "signin", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("view/"))))
router.HandleFunc("/", indexPage)
http.ListenAndServe(":8091", router)
}
HTML files: Have defined the header and footer in index.html which I refernce in the signin.html file
{{ define "header"}}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>User Sign in</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="/static/css/main.css">
<script src="/static/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
</head>
<body>
{{end}}
{{define "footer"}}
<footer class="panel-footer"><p>© Company 2016</p></footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="/static/js/vendor/bootstrap.min.js"></script>
<script src="/static/js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
{{end}}
signin.html file:
{{define "signin"}}
{{template "header" .}}
<h1 class="alert alert-info">Login</h1>
<div class="container">
{{with .Errors.message}}
<div class="alert alert-danger">
{{.}}
</div>
{{end}}
<form method="POST" action="/">
<label class="form-control" for="uname">User Name</label>
<input class="form-control" type="text" id="uname" name="uname">
<label class="form-control" for="password">Password</label>
<input class="form-control" type="password" id="password" name="password">
<button class="btn btn-info" type="submit">Submit</button>
</form>
{{template "footer" .}}
{{end}}
Why is it that this doesn't work when I place the html files in the sub-directory 'views'. The only thing that changes is the argument to parseGlob.
I believe all you need to do is remove this line:
router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("view/"))))
Works for me. Though you need to clean up your html a bit too - I see at least a missing </div>.
Templates are processed on the server and do not need to be served over internet. At the same time this route entry conflicts with the following one (indexPage) which defines another handler for the same route entry ("/"). So when you open it in a browser, server just send template files over internet. While indexPage handler is never called as directory handler is matched first.
Also you talking about "views" folder, but you code says "view" (without 's' at the end). Could be another simple reason.

Resources